concordium-rust-sdk 9.0.1

An SDK to use the Concordium blockchain.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
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
//! This module exposes [Client] which is a wrapper around the
//! generated gRPC rust client, providing a more ergonomic interface than the
//! generated client. See [Client] for documentation of how to use.
use crate::{
    endpoints,
    id::{self, types::AccountCredentialMessage},
    protocol_level_tokens,
    types::{
        self, block_certificates,
        chain_parameters::ChainParameters,
        hashes::{self, BlockHash, TransactionHash, TransactionSignHash},
        queries::ConsensusDetailedStatus,
        smart_contracts::{
            ContractContext, InstanceInfo, InvokeContractResult, ModuleReference, WasmModule,
        },
        transactions::{self, InitContractPayload, UpdateContractPayload, UpdateInstruction},
        AbsoluteBlockHeight, AccountInfo, AccountPending, BlockItemSummary,
        CredentialRegistrationID, Energy, Memo, Nonce, RegisteredData, SpecialTransactionOutcome,
        TransactionStatus, UpdateSequenceNumber,
    },
};
use anyhow::Context;
pub use concordium_base::common::upward::{self, Upward};
use concordium_base::{
    base::{AccountIndex, BlockHeight, Epoch, GenesisIndex},
    common::{
        self,
        types::{TransactionSignature, TransactionSignaturesV1, TransactionTime},
    },
    contracts_common::{
        AccountAddress, AccountAddressParseError, Amount, ContractAddress, OwnedContractName,
        OwnedParameter, OwnedReceiveName, ReceiveName,
    },
    hashes::HashFromStrError,
    transactions::{BlockItem, EncodedPayload, PayloadLike},
};
pub use endpoints::{QueryError, QueryResult, RPCError, RPCResult};
use futures::{Stream, StreamExt, TryStreamExt};
pub use http::uri::Scheme;
use std::{collections::HashMap, num::ParseIntError, str::FromStr};
use tonic::IntoRequest;
pub use tonic::{
    transport::{Endpoint, Error},
    Code, Status,
};

use self::dry_run::WithRemainingQuota;

mod conversions;
pub mod dry_run;
#[path = "generated/mod.rs"]
#[allow(
    clippy::large_enum_variant,
    clippy::enum_variant_names,
    clippy::derive_partial_eq_without_eq
)]
#[rustfmt::skip]
mod gen;
pub use gen::concordium::v2 as generated;
pub mod proto_schema_version;

/// A client for gRPC API v2 of the Concordium node. Can be used to control the
/// node, send transactions and query information about the node and the state
/// of the chain.
///
/// # Connecting to a Concordium node
///
/// Creates a new client connection to a Concordium node.
/// Make sure to have access to the gRPC API v2 endpoint of a running node.
///
/// ```no_run
/// # tokio_test::block_on(async {
/// use concordium_rust_sdk::v2::{Client, Endpoint};
/// use std::str::FromStr;
///
/// // Assumes the node is running locally and gRPC API v2 can be accessed on port 20001.
/// let node_endpoint = Endpoint::from_str("http://localhost:20001")?;
/// let mut client = Client::new(node_endpoint).await?;
///
/// // Verify the connection to the node by printing node information.
/// let node_info = client.get_node_info().await?;
/// println!("{:#?}", node_info);
/// # Ok::<(), anyhow::Error>(())
/// # });
/// ```
///
/// # Concurrent use of the client
///
/// All endpoints take a `&mut self` as an argument which means that a single
/// instance cannot be used concurrently. However instead of putting the Client
/// behind a Mutex, the intended way to use it is to clone it. Cloning is very
/// cheap and will reuse the underlying connection.
#[derive(Clone, Debug)]
pub struct Client {
    client: generated::queries_client::QueriesClient<tonic::transport::Channel>,
}

/// A query response with the addition of the block hash used by the query.
/// The block hash used for querying might be unknown when providing the block
/// as [BlockIdentifier::Best] or [BlockIdentifier::LastFinal].
#[derive(Clone, Copy, Debug)]
pub struct QueryResponse<A> {
    /// Block hash for which the query applies.
    pub block_hash: BlockHash,
    /// The result of the query.
    pub response: A,
}

impl<A> AsRef<A> for QueryResponse<A> {
    fn as_ref(&self) -> &A {
        &self.response
    }
}

/// A block identifier used in queries.
#[derive(Copy, Clone, Debug, derive_more::From, PartialEq, Eq)]
pub enum BlockIdentifier {
    /// Query in the context of the best block.
    Best,
    /// Query in the context of the last finalized block at the time of the
    /// query.
    LastFinal,
    /// Query in the context of a specific block hash.
    Given(BlockHash),
    /// Query for a block at absolute height. If a unique
    /// block can not be identified at that height the query will return
    /// `NotFound`.
    AbsoluteHeight(AbsoluteBlockHeight),
    /// Query for a block at a height relative to genesis index. If a unique
    /// block can not be identified at that height the query will return
    /// `NotFound`.
    RelativeHeight(RelativeBlockHeight),
}

#[derive(Debug, thiserror::Error)]
pub enum BlockIdentifierFromStrError {
    #[error("The input is not recognized.")]
    InvalidFormat,
    #[error("The input is not a valid hash: {0}.")]
    InvalidHash(#[from] HashFromStrError),
    #[error("The input is not a valid unsigned integer: {0}.")]
    InvalidInteger(#[from] ParseIntError),
}

/// Display implementation to match the [`FromStr`] implementation defined just
/// below.
impl std::fmt::Display for BlockIdentifier {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            BlockIdentifier::Best => "best".fmt(f),
            BlockIdentifier::LastFinal => "lastfinal".fmt(f),
            BlockIdentifier::Given(bh) => bh.fmt(f),
            BlockIdentifier::AbsoluteHeight(h) => write!(f, "@{h}"),
            BlockIdentifier::RelativeHeight(rh) => {
                write!(
                    f,
                    "@{}/{}{}",
                    rh.height,
                    rh.genesis_index,
                    if rh.restrict { "!" } else { "" }
                )
            }
        }
    }
}

/// Parse a string as a [`BlockIdentifier`]. The format is one of the following
///
/// - the string `best` for [`Best`](BlockIdentifier::Best)
/// - the string `lastFinal` or `lastfinal` for
///   [`LastFinal`](BlockIdentifier::LastFinal)
/// - a valid block hash for [`Given`](BlockIdentifier::Given)
/// - a string starting with `@` followed by an integer and nothing else for
///   [`AbsoluteHeight`](BlockIdentifier::AbsoluteHeight)
/// - a string in the format `@123/3` optionally followed by `!` where `123` is
///   the block height and `3` is the genesis index for
///   [`RelativeHeight`](BlockIdentifier::RelativeHeight). If `!` is present
///   then `restrict` is set to `true`.
impl std::str::FromStr for BlockIdentifier {
    type Err = BlockIdentifierFromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "best" => Ok(Self::Best),
            "lastFinal" => Ok(Self::LastFinal),
            "lastfinal" => Ok(Self::LastFinal),
            _ => {
                if let Some(rest) = s.strip_prefix('@') {
                    if let Some((height_str, gen_idx_str)) = rest.split_once('/') {
                        let height = BlockHeight::from_str(height_str)?;
                        if let Some(gen_idx) = gen_idx_str.strip_suffix('!') {
                            let genesis_index = GenesisIndex::from_str(gen_idx)?;
                            Ok(Self::RelativeHeight(RelativeBlockHeight {
                                genesis_index,
                                height,
                                restrict: true,
                            }))
                        } else {
                            let genesis_index = GenesisIndex::from_str(gen_idx_str)?;
                            Ok(Self::RelativeHeight(RelativeBlockHeight {
                                genesis_index,
                                height,
                                restrict: false,
                            }))
                        }
                    } else {
                        let h = AbsoluteBlockHeight::from_str(rest)?;
                        Ok(Self::AbsoluteHeight(h))
                    }
                } else {
                    let h = BlockHash::from_str(s)?;
                    Ok(Self::Given(h))
                }
            }
        }
    }
}

/// Block height relative to an explicit genesis index.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct RelativeBlockHeight {
    /// Genesis index to start from.
    pub genesis_index: types::GenesisIndex,
    /// Height starting from the genesis block at the genesis index.
    pub height: types::BlockHeight,
    /// Whether to return results only from the specified genesis index
    /// (`true`), or allow results from more recent genesis indices
    /// as well (`false`).
    pub restrict: bool,
}

/// An account identifier used in queries.
#[derive(Copy, Clone, Debug, derive_more::From, derive_more::Display)]
pub enum AccountIdentifier {
    /// Identify an account by an address.
    #[display(fmt = "{_0}")]
    Address(AccountAddress),
    /// Identify an account by the credential registration id.
    #[display(fmt = "{_0}")]
    CredId(CredentialRegistrationID),
    /// Identify an account by its account index.
    #[display(fmt = "{_0}")]
    Index(crate::types::AccountIndex),
}

impl FromStr for AccountIdentifier {
    type Err = AccountAddressParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(ai) = s.parse::<crate::types::AccountIndex>() {
            return Ok(Self::Index(ai));
        }
        if let Ok(cid) = s.parse::<CredentialRegistrationID>() {
            return Ok(Self::CredId(cid));
        }
        s.parse().map(Self::Address)
    }
}

/// Identifier for an [`Epoch`] relative to the specified genesis index.
#[derive(Debug, Copy, Clone)]
pub struct SpecifiedEpoch {
    /// Genesis index to query in.
    pub genesis_index: types::GenesisIndex,
    /// The epoch of the genesis to query.
    pub epoch: types::Epoch,
}

/// An identifier of an epoch used in queries.
#[derive(Copy, Clone, Debug, derive_more::From)]
pub enum EpochIdentifier {
    /// A specified epoch to query.
    Specified(SpecifiedEpoch),
    /// Query the epoch of the block.
    Block(BlockIdentifier),
}

/// Errors that may occur as a result of
/// parsing a [`EpochIdentifier`] from a string via
/// [from_str(&str)][std::str::FromStr].
#[derive(Debug, thiserror::Error)]
pub enum EpochIdentifierFromStrError {
    #[error("The input is not recognized.")]
    InvalidFormat,
    #[error("The genesis index is not a valid unsigned integer")]
    InvalidGenesis,
    #[error("The epoch index is not a valid unsigned integer")]
    InvalidEpoch,
    #[error("The input is not a valid block identifier: {0}.")]
    InvalidBlockIdentifier(#[from] BlockIdentifierFromStrError),
}

/// Parse a string as an [`EpochIdentifier`]. The format is one of the
/// following:
///
/// - a string starting with `%` followed by two integers separated by `,` for
///   [`Specified`](EpochIdentifier::Specified). First component is treated as
///   the genesis index and the second component as the epoch.
/// - a string starting with `@` followed by a [`BlockIdentifier`] for
///   [`Block`](EpochIdentifier::Block).
impl std::str::FromStr for EpochIdentifier {
    type Err = EpochIdentifierFromStrError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Some(rest) = s.strip_prefix('%') {
            if let Some((gen_idx_str, epoch_str)) = rest.split_once(',') {
                let genesis_index = GenesisIndex::from_str(gen_idx_str)
                    .map_err(|_| EpochIdentifierFromStrError::InvalidGenesis)?;
                let epoch = Epoch::from_str(epoch_str)
                    .map_err(|_| EpochIdentifierFromStrError::InvalidEpoch)?;
                Ok(Self::Specified(SpecifiedEpoch {
                    genesis_index,
                    epoch,
                }))
            } else {
                Err(EpochIdentifierFromStrError::InvalidFormat)
            }
        } else {
            Ok(Self::Block(BlockIdentifier::from_str(s)?))
        }
    }
}

impl IntoRequest<generated::EpochRequest> for &EpochIdentifier {
    fn into_request(self) -> tonic::Request<generated::EpochRequest> {
        tonic::Request::new((*self).into())
    }
}

impl From<EpochIdentifier> for generated::EpochRequest {
    fn from(ei: EpochIdentifier) -> Self {
        match ei {
            EpochIdentifier::Specified(SpecifiedEpoch {
                genesis_index,
                epoch,
            }) => generated::EpochRequest {
                epoch_request_input: Some(
                    generated::epoch_request::EpochRequestInput::RelativeEpoch(
                        generated::epoch_request::RelativeEpoch {
                            genesis_index: Some(generated::GenesisIndex {
                                value: genesis_index.height,
                            }),
                            epoch: Some(generated::Epoch { value: epoch.epoch }),
                        },
                    ),
                ),
            },
            EpochIdentifier::Block(bi) => generated::EpochRequest {
                epoch_request_input: Some(generated::epoch_request::EpochRequestInput::BlockHash(
                    (&bi).into(),
                )),
            },
        }
    }
}

/// Information of a finalized block.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct FinalizedBlockInfo {
    /// The block hash for the finalized block.
    pub block_hash: BlockHash,
    /// The absolute block height for the finalized block.
    pub height: AbsoluteBlockHeight,
}

impl From<&BlockIdentifier> for generated::BlockHashInput {
    fn from(bi: &BlockIdentifier) -> Self {
        let block_hash_input = match bi {
            BlockIdentifier::Best => {
                generated::block_hash_input::BlockHashInput::Best(Default::default())
            }
            BlockIdentifier::LastFinal => {
                generated::block_hash_input::BlockHashInput::LastFinal(Default::default())
            }
            BlockIdentifier::Given(h) => {
                generated::block_hash_input::BlockHashInput::Given(generated::BlockHash {
                    value: h.as_ref().to_vec(),
                })
            }
            &BlockIdentifier::AbsoluteHeight(h) => {
                generated::block_hash_input::BlockHashInput::AbsoluteHeight(h.into())
            }
            &BlockIdentifier::RelativeHeight(h) => {
                generated::block_hash_input::BlockHashInput::RelativeHeight(h.into())
            }
        };
        generated::BlockHashInput {
            block_hash_input: Some(block_hash_input),
        }
    }
}

impl IntoRequest<generated::BlockHashInput> for &BlockIdentifier {
    fn into_request(self) -> tonic::Request<generated::BlockHashInput> {
        tonic::Request::new(self.into())
    }
}

impl From<&AccountAddress> for generated::AccountAddress {
    fn from(addr: &AccountAddress) -> Self {
        generated::AccountAddress {
            value: concordium_base::common::to_bytes(addr),
        }
    }
}

impl From<AccountAddress> for generated::AccountAddress {
    fn from(addr: AccountAddress) -> Self {
        generated::AccountAddress {
            value: common::to_bytes(&addr),
        }
    }
}

impl From<&super::types::Address> for generated::Address {
    fn from(addr: &super::types::Address) -> Self {
        let ty = match addr {
            super::types::Address::Account(account) => {
                generated::address::Type::Account(account.into())
            }
            super::types::Address::Contract(contract) => {
                generated::address::Type::Contract(contract.into())
            }
        };
        generated::Address { r#type: Some(ty) }
    }
}

impl From<&Memo> for generated::Memo {
    fn from(v: &Memo) -> Self {
        Self {
            value: v.as_ref().clone(),
        }
    }
}

impl<'a> From<ReceiveName<'a>> for generated::ReceiveName {
    fn from(a: ReceiveName<'a>) -> Self {
        generated::ReceiveName {
            value: a.get_chain_name().to_string(),
        }
    }
}

impl From<&RegisteredData> for generated::RegisteredData {
    fn from(v: &RegisteredData) -> Self {
        Self {
            value: v.as_ref().clone(),
        }
    }
}
impl From<&[u8]> for generated::Parameter {
    fn from(a: &[u8]) -> Self {
        generated::Parameter { value: a.to_vec() }
    }
}

impl From<&TransactionHash> for generated::TransactionHash {
    fn from(th: &TransactionHash) -> Self {
        generated::TransactionHash { value: th.to_vec() }
    }
}

impl From<&AccountIdentifier> for generated::AccountIdentifierInput {
    fn from(ai: &AccountIdentifier) -> Self {
        let account_identifier_input = match ai {
            AccountIdentifier::Address(addr) => {
                generated::account_identifier_input::AccountIdentifierInput::Address(addr.into())
            }
            AccountIdentifier::CredId(credid) => {
                let credid = generated::CredentialRegistrationId {
                    value: concordium_base::common::to_bytes(credid),
                };
                generated::account_identifier_input::AccountIdentifierInput::CredId(credid)
            }
            AccountIdentifier::Index(index) => {
                generated::account_identifier_input::AccountIdentifierInput::AccountIndex(
                    (*index).into(),
                )
            }
        };
        generated::AccountIdentifierInput {
            account_identifier_input: Some(account_identifier_input),
        }
    }
}

impl From<&ModuleReference> for generated::ModuleRef {
    fn from(mr: &ModuleReference) -> Self {
        Self { value: mr.to_vec() }
    }
}

impl From<ModuleReference> for generated::ModuleRef {
    fn from(mr: ModuleReference) -> Self {
        Self { value: mr.to_vec() }
    }
}

impl From<&WasmModule> for generated::VersionedModuleSource {
    fn from(v: &WasmModule) -> Self {
        Self {
            module: Some(match v.version {
                types::smart_contracts::WasmVersion::V0 => {
                    generated::versioned_module_source::Module::V0(
                        generated::versioned_module_source::ModuleSourceV0 {
                            value: v.source.as_ref().clone(),
                        },
                    )
                }
                types::smart_contracts::WasmVersion::V1 => {
                    generated::versioned_module_source::Module::V1(
                        generated::versioned_module_source::ModuleSourceV1 {
                            value: v.source.as_ref().clone(),
                        },
                    )
                }
            }),
        }
    }
}

impl From<&OwnedContractName> for generated::InitName {
    fn from(v: &OwnedContractName) -> Self {
        Self {
            value: v.as_contract_name().get_chain_name().to_string(),
        }
    }
}

impl From<&OwnedReceiveName> for generated::ReceiveName {
    fn from(v: &OwnedReceiveName) -> Self {
        Self {
            value: v.as_receive_name().get_chain_name().to_string(),
        }
    }
}

impl From<&OwnedParameter> for generated::Parameter {
    fn from(v: &OwnedParameter) -> Self {
        Self {
            value: v.as_ref().to_vec(),
        }
    }
}

impl From<&InitContractPayload> for generated::InitContractPayload {
    fn from(v: &InitContractPayload) -> Self {
        Self {
            amount: Some(v.amount.into()),
            module_ref: Some(v.mod_ref.into()),
            init_name: Some((&v.init_name).into()),
            parameter: Some((&v.param).into()),
        }
    }
}

impl From<&UpdateContractPayload> for generated::UpdateContractPayload {
    fn from(v: &UpdateContractPayload) -> Self {
        Self {
            amount: Some(v.amount.into()),
            address: Some(v.address.into()),
            receive_name: Some((&v.receive_name).into()),
            parameter: Some((&v.message).into()),
        }
    }
}

impl From<&ContractAddress> for generated::ContractAddress {
    fn from(ca: &ContractAddress) -> Self {
        Self {
            index: ca.index,
            subindex: ca.subindex,
        }
    }
}

impl From<Nonce> for generated::SequenceNumber {
    fn from(v: Nonce) -> Self {
        generated::SequenceNumber { value: v.nonce }
    }
}

impl From<UpdateSequenceNumber> for generated::UpdateSequenceNumber {
    fn from(v: UpdateSequenceNumber) -> Self {
        generated::UpdateSequenceNumber { value: v.number }
    }
}

impl From<Energy> for generated::Energy {
    fn from(v: Energy) -> Self {
        generated::Energy { value: v.energy }
    }
}

impl From<TransactionTime> for generated::TransactionTime {
    fn from(v: TransactionTime) -> Self {
        generated::TransactionTime { value: v.seconds }
    }
}

impl From<&Amount> for generated::Amount {
    fn from(v: &Amount) -> Self {
        Self { value: v.micro_ccd }
    }
}

impl From<Amount> for generated::Amount {
    fn from(v: Amount) -> Self {
        Self { value: v.micro_ccd }
    }
}

impl
    From<
        &AccountCredentialMessage<
            id::constants::IpPairing,
            id::constants::ArCurve,
            id::constants::AttributeKind,
        >,
    > for generated::CredentialDeployment
{
    fn from(
        v: &AccountCredentialMessage<
            id::constants::IpPairing,
            id::constants::ArCurve,
            id::constants::AttributeKind,
        >,
    ) -> Self {
        Self {
            message_expiry: Some(v.message_expiry.into()),
            payload: Some(generated::credential_deployment::Payload::RawPayload(
                common::to_bytes(&v.credential),
            )),
        }
    }
}

impl From<&UpdateInstruction> for generated::UpdateInstruction {
    fn from(v: &UpdateInstruction) -> Self {
        Self {
            signatures: Some(generated::SignatureMap {
                signatures: {
                    let mut hm = HashMap::new();
                    for (key_idx, sig) in v.signatures.signatures.iter() {
                        hm.insert(
                            key_idx.index.into(),
                            generated::Signature {
                                value: sig.sig.to_owned(),
                            },
                        );
                    }
                    hm
                },
            }),
            header: Some(generated::UpdateInstructionHeader {
                sequence_number: Some(v.header.seq_number.into()),
                effective_time: Some(v.header.effective_time.into()),
                timeout: Some(v.header.timeout.into()),
            }),
            payload: Some(generated::UpdateInstructionPayload {
                payload: Some(generated::update_instruction_payload::Payload::RawPayload(
                    common::to_bytes(&v.payload),
                )),
            }),
        }
    }
}

impl IntoRequest<generated::AccountInfoRequest> for (&AccountIdentifier, &BlockIdentifier) {
    fn into_request(self) -> tonic::Request<generated::AccountInfoRequest> {
        let ai = generated::AccountInfoRequest {
            block_hash: Some(self.1.into()),
            account_identifier: Some(self.0.into()),
        };
        tonic::Request::new(ai)
    }
}

impl IntoRequest<generated::AncestorsRequest> for (&BlockIdentifier, u64) {
    fn into_request(self) -> tonic::Request<generated::AncestorsRequest> {
        let ar = generated::AncestorsRequest {
            block_hash: Some(self.0.into()),
            amount: self.1,
        };
        tonic::Request::new(ar)
    }
}

impl IntoRequest<generated::ModuleSourceRequest> for (&ModuleReference, &BlockIdentifier) {
    fn into_request(self) -> tonic::Request<generated::ModuleSourceRequest> {
        let r = generated::ModuleSourceRequest {
            block_hash: Some(self.1.into()),
            module_ref: Some(self.0.into()),
        };
        tonic::Request::new(r)
    }
}

impl IntoRequest<generated::InstanceInfoRequest> for (ContractAddress, &BlockIdentifier) {
    fn into_request(self) -> tonic::Request<generated::InstanceInfoRequest> {
        let r = generated::InstanceInfoRequest {
            block_hash: Some(self.1.into()),
            address: Some(self.0.into()),
        };
        tonic::Request::new(r)
    }
}

impl<V: Into<Vec<u8>>> IntoRequest<generated::InstanceStateLookupRequest>
    for (ContractAddress, &BlockIdentifier, V)
{
    fn into_request(self) -> tonic::Request<generated::InstanceStateLookupRequest> {
        let r = generated::InstanceStateLookupRequest {
            block_hash: Some(self.1.into()),
            address: Some(self.0.into()),
            key: self.2.into(),
        };
        tonic::Request::new(r)
    }
}

impl IntoRequest<generated::TransactionHash> for &TransactionHash {
    fn into_request(self) -> tonic::Request<generated::TransactionHash> {
        tonic::Request::new(self.into())
    }
}

impl IntoRequest<generated::AccountIdentifierInput> for &AccountIdentifier {
    fn into_request(self) -> tonic::Request<generated::AccountIdentifierInput> {
        tonic::Request::new(self.into())
    }
}

impl IntoRequest<generated::AccountAddress> for &AccountAddress {
    fn into_request(self) -> tonic::Request<generated::AccountAddress> {
        tonic::Request::new(self.into())
    }
}

impl From<transactions::TransactionHeader> for generated::AccountTransactionHeader {
    fn from(v: transactions::TransactionHeader) -> Self {
        (&v).into()
    }
}

impl From<&transactions::TransactionHeader> for generated::AccountTransactionHeader {
    fn from(v: &transactions::TransactionHeader) -> Self {
        Self {
            sender: Some(generated::AccountAddress::from(v.sender)),
            sequence_number: Some(v.nonce.into()),
            energy_amount: Some(v.energy_amount.into()),
            expiry: Some(v.expiry.into()),
        }
    }
}

impl From<&transactions::TransactionHeaderV1> for generated::AccountTransactionHeaderV1 {
    fn from(v: &transactions::TransactionHeaderV1) -> Self {
        Self {
            sender: Some(generated::AccountAddress::from(v.sender)),
            sponsor: v.sponsor.map(generated::AccountAddress::from),
            sequence_number: Some(v.nonce.into()),
            energy_amount: Some(v.energy_amount.into()),
            expiry: Some(v.expiry.into()),
        }
    }
}

impl From<TransactionSignature> for generated::AccountTransactionSignature {
    fn from(v: TransactionSignature) -> Self {
        (&v).into()
    }
}

impl From<&TransactionSignature> for generated::AccountTransactionSignature {
    fn from(v: &TransactionSignature) -> Self {
        Self {
            signatures: {
                let mut cred_map: HashMap<u32, generated::AccountSignatureMap> = HashMap::new();
                for (cred_idx, sig_map) in v.signatures.iter() {
                    let mut acc_sig_map: HashMap<u32, generated::Signature> = HashMap::new();
                    for (key_idx, sig) in sig_map.iter() {
                        acc_sig_map.insert(
                            key_idx.0.into(),
                            generated::Signature {
                                value: sig.sig.to_owned(),
                            },
                        );
                    }
                    cred_map.insert(
                        cred_idx.index.into(),
                        generated::AccountSignatureMap {
                            signatures: acc_sig_map,
                        },
                    );
                }
                cred_map
            },
        }
    }
}

impl From<&TransactionSignaturesV1> for generated::AccountTransactionV1Signatures {
    fn from(v: &TransactionSignaturesV1) -> Self {
        Self {
            sender_signatures: Some(v.sender.to_owned().into()),
            sponsor_signatures: v.sponsor.to_owned().map(|s| s.into()),
        }
    }
}

impl IntoRequest<generated::PreAccountTransaction>
    for (&transactions::TransactionHeader, &transactions::Payload)
{
    fn into_request(self) -> tonic::Request<generated::PreAccountTransaction> {
        let request = generated::PreAccountTransaction {
            header: Some(self.0.into()),
            payload: Some(generated::AccountTransactionPayload {
                payload: Some(generated::account_transaction_payload::Payload::RawPayload(
                    self.1.encode().into(),
                )),
            }),
        };
        tonic::Request::new(request)
    }
}

impl<P: PayloadLike> IntoRequest<generated::SendBlockItemRequest> for &transactions::BlockItem<P> {
    fn into_request(self) -> tonic::Request<generated::SendBlockItemRequest> {
        let request = match self {
            transactions::BlockItem::AccountTransaction(v) => {
                generated::SendBlockItemRequest {
                    block_item: Some(
                        generated::send_block_item_request::BlockItem::AccountTransaction(
                            generated::AccountTransaction {
                                signature: Some((&v.signature).into()),
                                header: Some((&v.header).into()),
                                payload: {
                                    let atp = generated::AccountTransactionPayload{
                                    payload: Some(generated::account_transaction_payload::Payload::RawPayload(v.payload.encode().into())),
                                };
                                    Some(atp)
                                },
                            },
                        ),
                    ),
                }
            }
            transactions::BlockItem::CredentialDeployment(v) => generated::SendBlockItemRequest {
                block_item: Some(
                    generated::send_block_item_request::BlockItem::CredentialDeployment(
                        v.as_ref().into(),
                    ),
                ),
            },
            transactions::BlockItem::UpdateInstruction(v) => generated::SendBlockItemRequest {
                block_item: Some(
                    generated::send_block_item_request::BlockItem::UpdateInstruction(v.into()),
                ),
            },
            transactions::BlockItem::AccountTransactionV1(v) => {
                generated::SendBlockItemRequest {
                    block_item: Some(
                        generated::send_block_item_request::BlockItem::AccountTransactionV1(
                            generated::AccountTransactionV1 {
                                signatures: Some((&v.signatures).into()),
                                header: Some((&v.header).into()),
                                payload: {
                                    let atp = generated::AccountTransactionPayload{
                                    payload: Some(generated::account_transaction_payload::Payload::RawPayload(v.payload.encode().into())),
                                };
                                    Some(atp)
                                },
                            },
                        ),
                    ),
                }
            }
        };
        tonic::Request::new(request)
    }
}

impl IntoRequest<generated::InvokeInstanceRequest> for (&BlockIdentifier, &ContractContext) {
    fn into_request(self) -> tonic::Request<generated::InvokeInstanceRequest> {
        let (block, context) = self;
        tonic::Request::new(generated::InvokeInstanceRequest {
            block_hash: Some(block.into()),
            invoker: context.invoker.as_ref().map(|a| a.into()),
            instance: Some((&context.contract).into()),
            amount: Some(context.amount.into()),
            entrypoint: Some(context.method.as_receive_name().into()),
            parameter: Some(context.parameter.as_ref().into()),
            energy: context.energy.map(From::from),
        })
    }
}

impl IntoRequest<generated::PoolInfoRequest> for (&BlockIdentifier, types::BakerId) {
    fn into_request(self) -> tonic::Request<generated::PoolInfoRequest> {
        let req = generated::PoolInfoRequest {
            block_hash: Some(self.0.into()),
            baker: Some(self.1.into()),
        };
        tonic::Request::new(req)
    }
}

impl IntoRequest<generated::BakerId> for types::BakerId {
    fn into_request(self) -> tonic::Request<generated::BakerId> {
        tonic::Request::new(generated::BakerId {
            value: self.id.index,
        })
    }
}

impl IntoRequest<generated::BlocksAtHeightRequest> for &endpoints::BlocksAtHeightInput {
    fn into_request(self) -> tonic::Request<generated::BlocksAtHeightRequest> {
        tonic::Request::new(self.into())
    }
}

impl IntoRequest<generated::GetPoolDelegatorsRequest> for (&BlockIdentifier, types::BakerId) {
    fn into_request(self) -> tonic::Request<generated::GetPoolDelegatorsRequest> {
        let req = generated::GetPoolDelegatorsRequest {
            block_hash: Some(self.0.into()),
            baker: Some(self.1.into()),
        };
        tonic::Request::new(req)
    }
}

impl TryFrom<crate::v2::generated::BannedPeer> for types::network::BannedPeer {
    type Error = anyhow::Error;

    fn try_from(value: crate::v2::generated::BannedPeer) -> Result<Self, Self::Error> {
        Ok(types::network::BannedPeer(
            <std::net::IpAddr as std::str::FromStr>::from_str(&value.ip_address.require()?.value)?,
        ))
    }
}

impl TryFrom<generated::IpSocketAddress> for std::net::SocketAddr {
    type Error = anyhow::Error;

    fn try_from(value: generated::IpSocketAddress) -> Result<Self, Self::Error> {
        Ok(std::net::SocketAddr::new(
            <std::net::IpAddr as std::str::FromStr>::from_str(&value.ip.require()?.value)?,
            value.port.require()?.value as u16,
        ))
    }
}

impl IntoRequest<crate::v2::generated::BannedPeer> for &types::network::BannedPeer {
    fn into_request(self) -> tonic::Request<crate::v2::generated::BannedPeer> {
        tonic::Request::new(crate::v2::generated::BannedPeer {
            ip_address: Some(crate::v2::generated::IpAddress {
                value: self.0.to_string(),
            }),
        })
    }
}

impl From<generated::PeerId> for types::network::PeerId {
    fn from(value: generated::PeerId) -> Self {
        types::network::PeerId(value.value)
    }
}

impl TryFrom<generated::PeersInfo> for types::network::PeersInfo {
    type Error = anyhow::Error;

    fn try_from(peers_info: generated::PeersInfo) -> Result<Self, Self::Error> {
        // Get information of the peers that the node is connected to.
        // Note. If one peer contains malformed data then this function does not
        // return any information about the others.
        // This should only happen in cases where the sdk and node is not on the same
        // major version.
        let peers = peers_info
            .peers
            .into_iter()
            .map(|peer| {
                // Parse the catchup status of the peer.
                let peer_consensus_info =
                    Upward::from(peer.consensus_info).and_then(|info| match info {
                        generated::peers_info::peer::ConsensusInfo::Bootstrapper(_) => {
                            Upward::Known(types::network::PeerConsensusInfo::Bootstrapper)
                        }
                        generated::peers_info::peer::ConsensusInfo::NodeCatchupStatus(status) => {
                            let Upward::Known(status) = Upward::from(
                                generated::peers_info::peer::CatchupStatus::try_from(status).ok(),
                            ) else {
                                return Upward::Known(types::network::PeerConsensusInfo::Node(
                                    Upward::Unknown(()),
                                ));
                            };
                            let status = match status {
                                generated::peers_info::peer::CatchupStatus::Uptodate => {
                                    types::network::PeerCatchupStatus::UpToDate
                                }
                                generated::peers_info::peer::CatchupStatus::Pending => {
                                    types::network::PeerCatchupStatus::Pending
                                }
                                generated::peers_info::peer::CatchupStatus::Catchingup => {
                                    types::network::PeerCatchupStatus::CatchingUp
                                }
                            };

                            Upward::Known(types::network::PeerConsensusInfo::Node(Upward::Known(
                                status,
                            )))
                        }
                    });
                // Parse the network statistics for the peer.
                let stats = peer.network_stats.require()?;
                let network_stats = types::network::NetworkStats {
                    packets_sent: stats.packets_sent,
                    packets_received: stats.packets_received,
                    latency: stats.latency,
                };
                Ok(types::network::Peer {
                    peer_id: peer.peer_id.require()?.into(),
                    consensus_info: peer_consensus_info,
                    network_stats,
                    addr: peer.socket_address.require()?.try_into()?,
                })
            })
            .collect::<anyhow::Result<Vec<types::network::Peer>>>()?;
        Ok(types::network::PeersInfo { peers })
    }
}

impl TryFrom<generated::node_info::NetworkInfo> for types::NetworkInfo {
    type Error = anyhow::Error;

    fn try_from(network_info: generated::node_info::NetworkInfo) -> Result<Self, Self::Error> {
        Ok(types::NetworkInfo {
            node_id: network_info.node_id.require()?.value,
            peer_total_sent: network_info.peer_total_sent,
            peer_total_received: network_info.peer_total_received,
            avg_bps_in: network_info.avg_bps_in,
            avg_bps_out: network_info.avg_bps_out,
        })
    }
}

impl IntoRequest<crate::v2::generated::PeerToBan> for types::network::PeerToBan {
    fn into_request(self) -> tonic::Request<crate::v2::generated::PeerToBan> {
        tonic::Request::new(match self {
            types::network::PeerToBan::IpAddr(ip_addr) => crate::v2::generated::PeerToBan {
                ip_address: Some(crate::v2::generated::IpAddress {
                    value: ip_addr.to_string(),
                }),
            },
        })
    }
}

impl TryFrom<generated::node_info::Details> for types::NodeDetails {
    type Error = anyhow::Error;

    fn try_from(details: generated::node_info::Details) -> Result<Self, Self::Error> {
        match details {
            generated::node_info::Details::Bootstrapper(_) => Ok(types::NodeDetails::Bootstrapper),
            generated::node_info::Details::Node(status) => {
                let Upward::Known(consensus_status) = Upward::from(status.consensus_status) else {
                    return Ok(types::NodeDetails::Node(Upward::Unknown(())));
                };
                let consensus_status = match consensus_status {
                    generated::node_info::node::ConsensusStatus::NotRunning(_) => {
                        types::NodeConsensusStatus::ConsensusNotRunning
                    }
                    generated::node_info::node::ConsensusStatus::Passive(_) => {
                        types::NodeConsensusStatus::ConsensusPassive
                    }
                    generated::node_info::node::ConsensusStatus::Active(baker) => {
                        let baker_id = baker.baker_id.require()?.into();
                        let Upward::Known(status) = Upward::from(baker.status) else {
                            return Ok(types::NodeDetails::Node(Upward::Unknown(())));
                        };

                        match status {
                            generated::node_info::baker_consensus_info::Status::PassiveCommitteeInfo(0) => types::NodeConsensusStatus::NotInCommittee(baker_id),
                            generated::node_info::baker_consensus_info::Status::PassiveCommitteeInfo(1) => types::NodeConsensusStatus::AddedButNotActiveInCommittee(baker_id),
                            generated::node_info::baker_consensus_info::Status::PassiveCommitteeInfo(2) => types::NodeConsensusStatus::AddedButWrongKeys(baker_id),
                            generated::node_info::baker_consensus_info::Status::ActiveBakerCommitteeInfo(_) => types::NodeConsensusStatus::Baker(baker_id),
                            generated::node_info::baker_consensus_info::Status::ActiveFinalizerCommitteeInfo(_) => types::NodeConsensusStatus::Finalizer(baker_id),
                            _ => anyhow::bail!("Malformed baker status")
                        }
                    }
                };
                Ok(types::NodeDetails::Node(Upward::Known(consensus_status)))
            }
        }
    }
}

impl TryFrom<generated::NodeInfo> for types::NodeInfo {
    type Error = anyhow::Error;

    fn try_from(node_info: generated::NodeInfo) -> Result<Self, Self::Error> {
        let version = semver::Version::parse(&node_info.peer_version)?;
        let local_time = chrono::DateTime::<chrono::Utc>::from(std::time::UNIX_EPOCH)
            + chrono::TimeDelta::try_milliseconds(node_info.local_time.require()?.value as i64)
                .context("Node local time out of bounds!")?;
        let uptime = chrono::Duration::try_from(types::DurationSeconds::from(
            node_info.peer_uptime.require()?.value,
        ))?;
        let network_info = node_info.network_info.require()?.try_into()?;
        let details = Upward::from(node_info.details)
            .map(types::NodeDetails::try_from)
            .transpose()?;
        Ok(types::NodeInfo {
            version,
            local_time,
            uptime,
            network_info,
            details,
        })
    }
}

/// A helper trait that is implemented by types that can be cheaply converted to
/// a [`BlockIdentifier`]. This is esentially [`Into<BlockIdentifier>`] but
/// orphan rules prevent using that exactly.
///
/// This trait makes it convenient to use block hashes as input to functions
/// that take a block identifier.
pub trait IntoBlockIdentifier {
    fn into_block_identifier(self) -> BlockIdentifier;
}

impl IntoBlockIdentifier for BlockIdentifier {
    fn into_block_identifier(self) -> BlockIdentifier {
        self
    }
}

impl<X: IntoBlockIdentifier + Copy> IntoBlockIdentifier for &X {
    fn into_block_identifier(self) -> BlockIdentifier {
        (*self).into_block_identifier()
    }
}

impl IntoBlockIdentifier for BlockHash {
    fn into_block_identifier(self) -> BlockIdentifier {
        BlockIdentifier::Given(self)
    }
}

impl IntoBlockIdentifier for AbsoluteBlockHeight {
    fn into_block_identifier(self) -> BlockIdentifier {
        BlockIdentifier::AbsoluteHeight(self)
    }
}

impl IntoBlockIdentifier for RelativeBlockHeight {
    fn into_block_identifier(self) -> BlockIdentifier {
        BlockIdentifier::RelativeHeight(self)
    }
}

impl Client {
    /// Construct a new client connection to a concordium node.
    ///
    /// # Example
    /// Creates a new client. Note the example assumes access to a local running
    /// node.
    ///
    /// ```no_run
    /// # tokio_test::block_on(async {
    /// use concordium_rust_sdk::{endpoints::Endpoint, v2::Client};
    /// use std::str::FromStr;
    ///
    /// let mut client = Client::new("http://localhost:20001").await?;
    ///
    /// # Ok::<(), anyhow::Error>(())
    /// # });
    /// ```
    pub async fn new<E>(endpoint: E) -> Result<Self, tonic::transport::Error>
    where
        E: TryInto<tonic::transport::Endpoint>,
        E::Error: Into<Box<dyn std::error::Error + Send + Sync + 'static>>,
    {
        let client = generated::queries_client::QueriesClient::connect(endpoint).await?;
        Ok(Self { client })
    }

    /// Get the information for the given account in the given block. If either
    /// the block or the account do not exist [`QueryError::NotFound`] is
    /// returned.
    pub async fn get_account_info(
        &mut self,
        acc: &AccountIdentifier,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<AccountInfo>> {
        let response = self
            .client
            .get_account_info((acc, &bi.into_block_identifier()))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = AccountInfo::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get the next sequence number for the account, with information on how
    /// reliable the information is.
    pub async fn get_next_account_sequence_number(
        &mut self,
        account_address: &AccountAddress,
    ) -> endpoints::QueryResult<types::queries::AccountNonceResponse> {
        let response = self
            .client
            .get_next_account_sequence_number(account_address)
            .await?;
        let response = types::queries::AccountNonceResponse::try_from(response.into_inner())?;
        Ok(response)
    }

    /// Get information about the current state of consensus. This is an
    /// overview of the node's current view of the chain.
    pub async fn get_consensus_info(
        &mut self,
    ) -> endpoints::QueryResult<types::queries::ConsensusInfo> {
        let response = self
            .client
            .get_consensus_info(generated::Empty::default())
            .await?;
        let response = types::queries::ConsensusInfo::try_from(response.into_inner())?;
        Ok(response)
    }

    /// Get the currently used cryptographic parameters. If the block does
    /// not exist [`QueryError::NotFound`] is returned.
    pub async fn get_cryptographic_parameters(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<types::CryptographicParameters>> {
        let response = self
            .client
            .get_cryptographic_parameters(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::CryptographicParameters::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get the list of accounts in the given block.
    /// The stream will end when all accounts that exist in the state at the end
    /// of the given block have been returned. If the block does not exist
    /// [`QueryError::NotFound`] is returned.
    pub async fn get_account_list(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<AccountAddress, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_account_list(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|x| x.and_then(TryFrom::try_from));
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get a list of all smart contract modules. The stream will end
    /// when all modules that exist in the state at the end of the given
    /// block have been returned.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    pub async fn get_module_list(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<ModuleReference, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_module_list(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|x| x.and_then(TryFrom::try_from));
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the source of a smart contract module.
    /// If the block or module does not exist [`QueryError::NotFound`] is
    /// returned.
    pub async fn get_module_source(
        &mut self,
        module_ref: &ModuleReference,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<types::smart_contracts::WasmModule>> {
        let response = self
            .client
            .get_module_source((module_ref, &bi.into_block_identifier()))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::smart_contracts::WasmModule::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get the list of smart contract instances in a given block.
    /// The stream will end when all instances that exist in the state at the
    /// end of the given block have been returned. If the block does not
    /// exist [`QueryError::NotFound`] is returned.
    pub async fn get_instance_list(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<ContractAddress, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_instance_list(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|x| x.map(From::from));
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get information about a smart contract instance as it appears at the end
    /// of the given block. If the block or instance does not exist
    /// [`QueryError::NotFound`] is returned.
    pub async fn get_instance_info(
        &mut self,
        address: ContractAddress,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<InstanceInfo>> {
        let response = self
            .client
            .get_instance_info((address, &bi.into_block_identifier()))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = InstanceInfo::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get a stream of ancestors for the provided block.
    /// Starting with the provided block itself, moving backwards until no more
    /// ancestors or the requested number of ancestors have been returned.
    pub async fn get_ancestors(
        &mut self,
        bi: impl IntoBlockIdentifier,
        limit: u64,
    ) -> endpoints::QueryResult<QueryResponse<impl Stream<Item = Result<BlockHash, tonic::Status>>>>
    {
        let response = self
            .client
            .get_ancestors((&bi.into_block_identifier(), limit))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|x| x.and_then(TryFrom::try_from));
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Return a stream of blocks that are finalized from the time the query is
    /// made onward.
    /// This can be used to listen for newly finalized blocks.
    ///
    /// Note: There is no guarantee that blocks will not be skipped if the
    /// client is too slow in processing the stream, however blocks will
    /// always be sent by increasing block height.
    pub async fn get_finalized_blocks(
        &mut self,
    ) -> endpoints::QueryResult<impl Stream<Item = Result<FinalizedBlockInfo, tonic::Status>>> {
        let response = self
            .client
            .get_finalized_blocks(generated::Empty::default())
            .await?;
        let stream = response.into_inner().map(|x| match x {
            Ok(v) => {
                let block_hash = v.hash.require().and_then(TryFrom::try_from)?;
                let height = v.height.require()?.into();
                Ok(FinalizedBlockInfo { block_hash, height })
            }
            Err(x) => Err(x),
        });
        Ok(stream)
    }

    /// Get the exact state of a specific contract instance, streamed as a list
    /// of key-value pairs. The list is streamed in lexicographic order of
    /// keys.
    /// If the block or instance does not exist [`QueryError::NotFound`] is
    /// returned.
    pub async fn get_instance_state(
        &mut self,
        ca: ContractAddress,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<(Vec<u8>, Vec<u8>), tonic::Status>>>,
    > {
        let response = self
            .client
            .get_instance_state((ca, &bi.into_block_identifier()))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|x| match x {
            Ok(v) => {
                let key = v.key;
                let value = v.value;
                Ok((key, value))
            }
            Err(x) => Err(x),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the value at a specific key of a contract state. In contrast to
    /// [`get_instance_state`](Self::get_instance_state) this is more efficient,
    /// but requires the user to know the specific key to look for.
    /// If the block or instance does not exist [`QueryError::NotFound`] is
    /// returned.
    pub async fn instance_state_lookup(
        &mut self,
        ca: ContractAddress,
        key: impl Into<Vec<u8>>,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<Vec<u8>>> {
        let response = self
            .client
            .instance_state_lookup((ca, &bi.into_block_identifier(), key))
            .await?;
        let block_hash = extract_metadata(&response)?;
        Ok(QueryResponse {
            block_hash,
            response: response.into_inner().value,
        })
    }

    /// Get the status of and information about a specific block item
    /// (transaction). If the block item does not exist
    /// [`QueryError::NotFound`] is returned.
    pub async fn get_block_item_status(
        &mut self,
        th: &TransactionHash,
    ) -> endpoints::QueryResult<TransactionStatus> {
        let response = self.client.get_block_item_status(th).await?;
        let response = TransactionStatus::try_from(response.into_inner())?;
        Ok(response)
    }

    /// Send a block item. A block item is either an `AccountTransaction`, which
    /// is a transaction signed and paid for by an account, a
    /// `CredentialDeployment`, which creates a new account, or
    /// `UpdateInstruction`, which is an instruction to change some
    /// parameters of the chain. Update instructions can only be sent by the
    /// governance committee.
    pub async fn send_block_item<P: PayloadLike>(
        &mut self,
        bi: &transactions::BlockItem<P>,
    ) -> endpoints::RPCResult<TransactionHash> {
        let response = self.client.send_block_item(bi).await?;
        let response = TransactionHash::try_from(response.into_inner())?;
        Ok(response)
    }

    /// Send an account transaction. This is just a helper around
    /// [`send_block_item`](Self::send_block_item) block item for convenience.
    pub async fn send_account_transaction<P: PayloadLike>(
        &mut self,
        at: transactions::AccountTransaction<P>,
    ) -> endpoints::RPCResult<TransactionHash> {
        self.send_block_item(&at.into()).await
    }

    /// Get the hash to be signed for an account transaction from the node. The
    /// hash returned can then be used for signing when constructing
    /// [`TransactionSignature`] as part of calling [`Client::send_block_item`].
    ///
    /// This is provided as a convenience to support cases where the right SDK
    /// is not available for interacting with the node.
    ///
    /// This SDK can compute the hash off-line and it is not recommended to use
    /// this endpoint, instead use [`compute_transaction_sign_hash`].
    ///
    /// [`compute_transaction_sign_hash`]:
    /// types::transactions::compute_transaction_sign_hash
    pub async fn get_account_transaction_sign_hash(
        &mut self,
        header: &transactions::TransactionHeader,
        payload: &transactions::Payload,
    ) -> endpoints::RPCResult<TransactionSignHash> {
        let response = self
            .client
            .get_account_transaction_sign_hash((header, payload))
            .await?;
        let response = TransactionSignHash::try_from(response.into_inner())?;
        Ok(response)
    }

    /// Wait until the transaction is finalized. Returns
    /// [`NotFound`](QueryError::NotFound) in case the transaction is not
    /// known to the node. In case of success, the return value is a pair of the
    /// block hash of the block that contains the transactions, and its
    /// outcome in the block.
    ///
    /// Since this can take an indefinite amount of time in general, users of
    /// this function might wish to wrap it inside
    /// [`timeout`](tokio::time::timeout) handler and handle the resulting
    /// failure.
    pub async fn wait_until_finalized(
        &mut self,
        hash: &types::hashes::TransactionHash,
    ) -> endpoints::QueryResult<(types::hashes::BlockHash, types::BlockItemSummary)> {
        let hash = *hash;
        let process_response = |response| {
            if let types::TransactionStatus::Finalized(blocks) = response {
                let mut iter = blocks.into_iter();
                if let Some(rv) = iter.next() {
                    if iter.next().is_some() {
                        Err(tonic::Status::internal(
                            "Finalized transaction finalized into multiple blocks. This cannot \
                             happen.",
                        )
                        .into())
                    } else {
                        Ok::<_, QueryError>(Some(rv))
                    }
                } else {
                    Err(tonic::Status::internal(
                        "Finalized transaction finalized into no blocks. This cannot happen.",
                    )
                    .into())
                }
            } else {
                Ok(None)
            }
        };

        match process_response(self.get_block_item_status(&hash).await?)? {
            Some(rv) => Ok(rv),
            None => {
                // if the first query did not succeed then start listening for finalized blocks.
                // and on each new block try to query the status.
                let mut blocks = self.get_finalized_blocks().await?;
                while blocks.next().await.transpose()?.is_some() {
                    if let Some(rv) = process_response(self.get_block_item_status(&hash).await?)? {
                        return Ok(rv);
                    }
                }
                Err(QueryError::NotFound)
            }
        }
    }

    /// Run the smart contract instance entrypoint in a given context and in the
    /// state at the end of the given block and return the results.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    pub async fn invoke_instance(
        &mut self,
        bi: impl IntoBlockIdentifier,
        context: &ContractContext,
    ) -> endpoints::QueryResult<QueryResponse<InvokeContractResult>> {
        let response = self
            .client
            .invoke_instance((&bi.into_block_identifier(), context))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = InvokeContractResult::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Start a dry-run sequence that can be used to simulate a series of
    /// transactions and other operations on the node.
    ///
    /// Before invoking any other operations on the [`dry_run::DryRun`] object,
    /// the state must be loaded by calling
    /// [`dry_run::DryRun::load_block_state`].
    pub async fn begin_dry_run(&mut self) -> endpoints::QueryResult<dry_run::DryRun> {
        Ok(dry_run::DryRun::new(&mut self.client).await?)
    }

    /// Start a dry-run sequence that can be used to simulate a series of
    /// transactions and other operations on the node, starting from the
    /// specified block.
    pub async fn dry_run(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> dry_run::DryRunResult<(dry_run::DryRun, dry_run::BlockStateLoaded)> {
        let mut runner = dry_run::DryRun::new(&mut self.client).await?;
        let load_result = runner.load_block_state(bi).await?;
        Ok(WithRemainingQuota {
            inner: (runner, load_result.inner),
            quota_remaining: load_result.quota_remaining,
        })
    }

    /// Get information, such as height, timings, and transaction counts for the
    /// given block. If the block does not exist [`QueryError::NotFound`] is
    /// returned.
    pub async fn get_block_info(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<types::queries::BlockInfo>> {
        let response = self
            .client
            .get_block_info(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::queries::BlockInfo::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get information about whether a block identified by `bi` is a payday
    /// block or not. This will always return `false` for blocks produced prior
    /// to protocol version 4. If the block does not exits
    /// [`QueryError::NotFound`] is returned.
    pub async fn is_payday_block(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<bool>> {
        let mut special_events = self.get_block_special_events(bi).await?;
        let block_hash = special_events.block_hash;

        while let Some(event) = special_events.response.next().await.transpose()? {
            let Upward::Known(event) = event else {
                // Ignore new unknown block special events.
                continue;
            };
            let has_payday_event = matches!(
                event,
                SpecialTransactionOutcome::PaydayPoolReward { .. }
                    | SpecialTransactionOutcome::PaydayAccountReward { .. }
                    | SpecialTransactionOutcome::PaydayFoundationReward { .. }
            );

            if has_payday_event {
                return Ok(QueryResponse {
                    block_hash,
                    response: true,
                });
            };
        }

        Ok(QueryResponse {
            block_hash,
            response: false,
        })
    }

    /// Get all the bakers at the end of the given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    pub async fn get_baker_list(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::BakerId, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_baker_list(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|x| x.map(From::from));
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get information about a given pool at the end of a given block.
    /// If the block does not exist or is prior to protocol version 4 then
    /// [`QueryError::NotFound`] is returned.
    pub async fn get_pool_info(
        &mut self,
        block_id: impl IntoBlockIdentifier,
        baker_id: types::BakerId,
    ) -> endpoints::QueryResult<QueryResponse<types::BakerPoolStatus>> {
        let response = self
            .client
            .get_pool_info((&block_id.into_block_identifier(), baker_id))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::BakerPoolStatus::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get information about the passive delegators at the end of a given
    /// block.
    /// If the block does not exist or is prior to protocol version 4 then
    /// [`QueryError::NotFound`] is returned.
    pub async fn get_passive_delegation_info(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<types::PassiveDelegationStatus>> {
        let response = self
            .client
            .get_passive_delegation_info(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::PassiveDelegationStatus::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get a list of live blocks at a given height.
    pub async fn get_blocks_at_height(
        &mut self,
        blocks_at_height_input: &endpoints::BlocksAtHeightInput,
    ) -> endpoints::QueryResult<Vec<BlockHash>> {
        let response = self
            .client
            .get_blocks_at_height(blocks_at_height_input)
            .await?;
        let blocks = response
            .into_inner()
            .blocks
            .into_iter()
            .map(TryFrom::try_from)
            .collect::<Result<_, tonic::Status>>()?;
        Ok(blocks)
    }

    /// Get information about tokenomics at the end of a given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    pub async fn get_tokenomics_info(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<types::RewardsOverview>> {
        let response = self
            .client
            .get_tokenomics_info(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::RewardsOverview::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get the registered delegators of a given pool at the end of a given
    /// block.
    /// If the block or baker ID does not exist [`QueryError::NotFound`] is
    /// returned, and if the block is baked prior to protocol version 4
    /// [`QueryError::RPCError`] with status [`Code::InvalidArgument`] is
    /// returned. The stream will end when all the delegators have been
    /// returned for the given block.
    ///
    /// In contrast to the [Client::get_pool_delegators_reward_period] which
    /// returns delegators that are fixed for the reward period of the
    /// block, this endpoint returns the list of delegators that are
    /// registered in the block. Any changes to delegators are immediately
    /// visible in this list.
    pub async fn get_pool_delegators(
        &mut self,
        bi: impl IntoBlockIdentifier,
        baker_id: types::BakerId,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::DelegatorInfo, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_pool_delegators((&bi.into_block_identifier(), baker_id))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(delegator) => delegator.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the fixed delegators of a given pool for the reward period of the
    /// given block.
    /// If the block or baker ID does not exist [`QueryError::NotFound`] is
    /// returned, and if the block is baked prior to protocol version 4
    /// [`QueryError::RPCError`] with status [`Code::InvalidArgument`] is
    /// returned. The stream will end when all the delegators have been
    /// returned.
    ///
    /// In contrast to the [Client::get_pool_delegators] which
    /// returns delegators registered for the given block, this endpoint
    /// returns the fixed delegators contributing stake in the reward period
    /// containing the given block.
    pub async fn get_pool_delegators_reward_period(
        &mut self,
        bi: impl IntoBlockIdentifier,
        baker_id: types::BakerId,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::DelegatorRewardPeriodInfo, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_pool_delegators_reward_period((&bi.into_block_identifier(), baker_id))
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(delegator) => delegator.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the registered passive delegators at the end of a given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned, and if
    /// the block is baked prior to protocol version 4 [`QueryError::
    /// RPCError`] with status [`Code::InvalidArgument`] is returned. The stream
    /// will end when all the delegators have been returned.
    ///
    /// In contrast to the [`Client::get_passive_delegators_reward_period`]
    /// which returns delegators that are fixed for the reward period of the
    /// block, this endpoint returns the list of delegators that are
    /// registered in the block. Any changes to delegators are immediately
    /// visible in this list.
    pub async fn get_passive_delegators(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::DelegatorInfo, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_passive_delegators(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(delegator) => delegator.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the fixed passive delegators for the reward period of the given
    /// block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    /// If the block is baked prior to protocol version 4,
    /// [`QueryError::RPCError`] with status [`Code::InvalidArgument`] is
    /// returned. The stream will end when all the delegators have been
    /// returned.
    ///
    /// In contrast to the `GetPassiveDelegators` which returns delegators
    /// registered for the given block, this endpoint returns the fixed
    /// delegators contributing stake in the reward period containing the
    /// given block.
    pub async fn get_passive_delegators_reward_period(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::DelegatorRewardPeriodInfo, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_passive_delegators_reward_period(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(delegator) => delegator.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the current branches of blocks starting from and including the last
    /// finalized block.
    ///
    /// Branches are all live blocks that are successors of the last finalized
    /// block. In particular this means that blocks which do not have a
    /// parent are not included in this response.
    pub async fn get_branches(&mut self) -> endpoints::QueryResult<types::queries::Branch> {
        let response = self
            .client
            .get_branches(generated::Empty::default())
            .await?;
        let response = types::queries::Branch::try_from(response.into_inner())?;
        Ok(response)
    }

    /// Get information related to the baker election for a particular block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    pub async fn get_election_info(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<types::BirkParameters>> {
        let response = self
            .client
            .get_election_info(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::BirkParameters::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get the identity providers registered as of the end of a given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    /// The stream will end when all the identity providers have been returned.
    pub async fn get_identity_providers(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<
            impl Stream<
                Item = Result<
                    crate::id::types::IpInfo<crate::id::constants::IpPairing>,
                    tonic::Status,
                >,
            >,
        >,
    > {
        let response = self
            .client
            .get_identity_providers(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(ip_info) => ip_info.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the list of anonymity revokers in the given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    /// The stream will end when all the anonymity revokers have been returned.
    pub async fn get_anonymity_revokers(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<
            impl Stream<
                Item = Result<
                    crate::id::types::ArInfo<crate::id::constants::ArCurve>,
                    tonic::Status,
                >,
            >,
        >,
    > {
        let response = self
            .client
            .get_anonymity_revokers(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(ar_info) => ar_info.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the list of transactions hashes for transactions that claim to be
    /// from the given account, but which are not yet finalized.
    /// They are either committed to a block or still pending.
    /// The stream will end when all the non-finalized transaction hashes have
    /// been returned. If the account does not exist an empty list will be
    /// returned.
    ///
    /// This endpoint is not expected to return a large amount of data in most
    /// cases, but in bad network conditions it might.
    pub async fn get_account_non_finalized_transactions(
        &mut self,
        account_address: &AccountAddress,
    ) -> endpoints::QueryResult<impl Stream<Item = Result<TransactionHash, tonic::Status>>> {
        let response = self
            .client
            .get_account_non_finalized_transactions(account_address)
            .await?;
        let stream = response.into_inner().map(|result| match result {
            Ok(transaction_hash) => transaction_hash.try_into(),
            Err(err) => Err(err),
        });
        Ok(stream)
    }

    /// Get the block items included in a given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    /// The stream will end when all the block items in the given block have
    /// been returned.
    /// To allow for forward-compatibility [`Upward::Unknown`] is returned
    /// if/when encountering a unknown future type of [`BlockItem`].
    pub async fn get_block_items(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<Upward<BlockItem<EncodedPayload>>, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_block_items(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(summary) => summary.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the specific **block item** if it is finalized.
    /// If the transaction does not exist in a finalized block
    /// [`QueryError::NotFound`] is returned.
    ///
    /// **Note that this is not an efficient method** since the node API does
    /// not allow for retrieving just the specific block item, but rather
    /// requires retrieving the full block. Use it for testing and debugging
    /// only.
    ///
    /// The return value is a triple of the [`BlockItem`], the hash of the block
    /// in which it is finalized, and the outcome in the form of
    /// [`BlockItemSummary`].
    /// To allow for forward-compatibility [`Upward::Unknown`] is returned
    /// if/when encountering a unknown future type of [`BlockItem`].
    pub async fn get_finalized_block_item(
        &mut self,
        th: TransactionHash,
    ) -> endpoints::QueryResult<(
        Upward<BlockItem<EncodedPayload>>,
        BlockHash,
        BlockItemSummary,
    )> {
        let status = self.get_block_item_status(&th).await?;
        let Some((bh, status)) = status.is_finalized() else {
            return Err(QueryError::NotFound);
        };
        let mut response = self
            .client
            .get_block_items(&bh.into_block_identifier())
            .await?
            .into_inner();
        while let Some(tx) = response.try_next().await? {
            let tx_hash = TransactionHash::try_from(tx.hash.clone().require()?)?;
            if tx_hash == th {
                return Ok((tx.try_into()?, *bh, status.clone()));
            }
        }
        Err(endpoints::QueryError::NotFound)
    }

    /// Shut down the node.
    /// Return a GRPC error if the shutdown failed.
    pub async fn shutdown(&mut self) -> endpoints::RPCResult<()> {
        self.client.shutdown(generated::Empty::default()).await?;
        Ok(())
    }

    /// Suggest a peer to connect to the submitted peer details.
    /// This, if successful, adds the peer to the list of given addresses.
    /// Otherwise return a GRPC error.
    ///
    /// Note: The peer might not be connected to instantly, in that case
    /// the node will try to establish the connection in near future. This
    /// function returns a GRPC status 'Ok' in this case.
    pub async fn peer_connect(&mut self, addr: std::net::SocketAddr) -> endpoints::RPCResult<()> {
        let peer_connection = generated::IpSocketAddress {
            ip: Some(generated::IpAddress {
                value: addr.ip().to_string(),
            }),
            port: Some(generated::Port {
                value: addr.port() as u32,
            }),
        };
        self.client.peer_connect(peer_connection).await?;
        Ok(())
    }

    /// Disconnect from the peer and remove them from the given addresses list
    /// if they are on it. Return if the request was processed successfully.
    /// Otherwise return a GRPC error.
    pub async fn peer_disconnect(
        &mut self,
        addr: std::net::SocketAddr,
    ) -> endpoints::RPCResult<()> {
        let peer_connection = generated::IpSocketAddress {
            ip: Some(generated::IpAddress {
                value: addr.ip().to_string(),
            }),
            port: Some(generated::Port {
                value: addr.port() as u32,
            }),
        };
        self.client.peer_disconnect(peer_connection).await?;
        Ok(())
    }

    /// Get a vector of the banned peers.
    pub async fn get_banned_peers(
        &mut self,
    ) -> endpoints::RPCResult<Vec<super::types::network::BannedPeer>> {
        Ok(self
            .client
            .get_banned_peers(generated::Empty::default())
            .await?
            .into_inner()
            .peers
            .into_iter()
            .map(super::types::network::BannedPeer::try_from)
            .collect::<anyhow::Result<Vec<super::types::network::BannedPeer>>>()?)
    }

    /// Ban a peer.
    /// When successful return `Ok(())`, and otherwise return an error
    /// describing the issue.
    pub async fn ban_peer(
        &mut self,
        peer_to_ban: super::types::network::PeerToBan,
    ) -> endpoints::RPCResult<()> {
        self.client.ban_peer(peer_to_ban).await?;
        Ok(())
    }

    /// Unban a peer.
    /// When successful return `Ok(())`, and otherwise return an error
    /// describing the issue.
    pub async fn unban_peer(
        &mut self,
        banned_peer: &super::types::network::BannedPeer,
    ) -> endpoints::RPCResult<()> {
        self.client.unban_peer(banned_peer).await?;
        Ok(())
    }

    /// Start a network dump if the feature is enabled on the node.
    /// This writes all the network packets into the given file.
    /// Return `Ok(())` if a network dump has been initiated, and an error
    /// otherwise.
    ///
    /// * file - The file to write to.
    /// * raw - Whether raw packets should be included in the dump or not.
    ///
    /// Note. If the feature 'network_dump' is not enabled on the node then this
    /// will return a 'Precondition failed' error.
    pub async fn dump_start(
        &mut self,
        file: &std::path::Path,
        raw: bool,
    ) -> endpoints::RPCResult<()> {
        let file_str = file.to_str().ok_or_else(|| {
            tonic::Status::invalid_argument(
                "The provided path cannot is not a valid UTF8 string, so cannot be used.",
            )
        })?;

        self.client
            .dump_start(generated::DumpRequest {
                file: file_str.to_string(),
                raw,
            })
            .await?;
        Ok(())
    }

    /// Stop an ongoing network dump.
    /// Return nothing if it was successfully stopped, and otherwise return an
    /// error.
    ///
    /// Note. If the feature 'network_dump' is not enabled on the node then this
    /// will return a 'Precondition failed' error.
    pub async fn dump_stop(&mut self) -> endpoints::RPCResult<()> {
        self.client.dump_stop(generated::Empty::default()).await?;
        Ok(())
    }

    /// Get a list of the peers that the node is connected to and associated
    /// network related information for each peer.
    pub async fn get_peers_info(&mut self) -> endpoints::RPCResult<types::network::PeersInfo> {
        let response = self
            .client
            .get_peers_info(generated::Empty::default())
            .await?;
        let peers_info = types::network::PeersInfo::try_from(response.into_inner())?;
        Ok(peers_info)
    }

    /// Retrieve information about the node.
    /// The response contains meta information about the node
    /// such as the version of the software, the local time of the node etc.
    ///
    /// The response also yields network related information such as the node
    /// ID, bytes sent/received etc.
    ///
    /// Finally depending on the type of the node (regular node or
    /// 'bootstrapper') the response also yields baking information if
    /// the node is configured with baker credentials.
    ///
    /// Bootstrappers do no reveal any consensus information as they do not run
    /// the consensus protocol.
    pub async fn get_node_info(&mut self) -> endpoints::RPCResult<types::NodeInfo> {
        let response = self
            .client
            .get_node_info(generated::Empty::default())
            .await?;
        let node_info = types::NodeInfo::try_from(response.into_inner())?;
        Ok(node_info)
    }

    /// Get the projected earliest time a baker wins the opportunity to bake a
    /// block.
    /// If the baker is not a baker for the current reward period then then the
    /// timestamp returned is the projected time of the first block of the
    /// new reward period.
    /// Note that the endpoint is only available on a node running at least
    /// protocol version 6.
    pub async fn get_baker_earliest_win_time(
        &mut self,
        bid: types::BakerId,
    ) -> endpoints::RPCResult<chrono::DateTime<chrono::Utc>> {
        let ts = self.client.get_baker_earliest_win_time(bid).await?;
        let local_time = ts.into_inner().try_into()?;
        Ok(local_time)
    }

    /// Get the transaction events in a given block. If the block does not exist
    /// [`QueryError::NotFound`] is returned. The stream will end when all the
    /// transaction events for a given block have been returned.
    pub async fn get_block_transaction_events(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::BlockItemSummary, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_block_transaction_events(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(summary) => summary.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get a the special events in a given block. If the block does not exist
    /// [`QueryError::NotFound`] is returned. The stream will end when all the
    /// special events for a given block have been returned.
    ///
    /// These are events generated by the protocol, such as minting and reward
    /// payouts. They are not directly generated by any transaction.
    pub async fn get_block_special_events(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<
            impl Stream<Item = Result<Upward<types::SpecialTransactionOutcome>, tonic::Status>>,
        >,
    > {
        let response = self
            .client
            .get_block_special_events(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(summary) => summary.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the pending updates to chain parameters at the end of a given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    /// The stream will end when all the pending updates for a given block have
    /// been returned.
    pub async fn get_block_pending_updates(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::queries::PendingUpdate, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_block_pending_updates(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(update) => update.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the winning bakers of an historical `Epoch`.
    /// Hence, when this function is invoked using [`EpochIdentifier::Block`]
    /// and the [`BlockIdentifier`] is either [`BlockIdentifier::Best`] or
    /// [`BlockIdentifier::LastFinal`], then [`tonic::Code::Unavailable`] is
    /// returned, as these identifiers are not historical by definition.
    ///
    /// The stream ends when there
    /// are no more rounds for the epoch specified. This only works for
    /// epochs in at least protocol version 6. Note that the endpoint is
    /// only available on a node running at least protocol version 6.
    pub async fn get_winning_bakers_epoch(
        &mut self,
        ei: impl Into<EpochIdentifier>,
    ) -> endpoints::QueryResult<impl Stream<Item = Result<types::WinningBaker, tonic::Status>>>
    {
        let response = self.client.get_winning_bakers_epoch(&ei.into()).await?;
        let stream = response.into_inner().map(|result| match result {
            Ok(wb) => wb.try_into(),
            Err(err) => Err(err),
        });
        Ok(stream)
    }

    /// Get the first block of the epoch.
    pub async fn get_first_block_epoch(
        &mut self,
        ei: impl Into<EpochIdentifier>,
    ) -> endpoints::QueryResult<BlockHash> {
        let response = self.client.get_first_block_epoch(&ei.into()).await?;
        Ok(response.into_inner().try_into()?)
    }

    /// Get the detailed status of the consensus. This is only available for
    /// consensus version 1. If the genesis index is not specified, the
    /// status for the current genesis index is returned.
    pub async fn get_consensus_detailed_status(
        &mut self,
        genesis_index: Option<GenesisIndex>,
    ) -> endpoints::RPCResult<ConsensusDetailedStatus> {
        let query = generated::ConsensusDetailedStatusQuery {
            genesis_index: genesis_index.map(Into::into),
        };
        let response = self.client.get_consensus_detailed_status(query).await?;
        Ok(response.into_inner().try_into()?)
    }

    /// Get next available sequence numbers for updating chain parameters after
    /// a given block. If the block does not exist then [`QueryError::NotFound`]
    /// is returned.
    pub async fn get_next_update_sequence_numbers(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<types::queries::NextUpdateSequenceNumbers>> {
        let response = self
            .client
            .get_next_update_sequence_numbers(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = types::queries::NextUpdateSequenceNumbers::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get all accounts that have scheduled releases, with the timestamp of the
    /// first pending scheduled release for that account. (Note, this only
    /// identifies accounts by index, and only indicates the first pending
    /// release for each account.)
    pub async fn get_scheduled_release_accounts(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<AccountPending, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_scheduled_release_accounts(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(pending) => pending.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get all accounts that have stake in cooldown, with the timestamp of the
    /// first pending cooldown expiry for each account. (Note, this only
    /// identifies accounts by index, and only indicates the first pending
    /// cooldown for each account.) Prior to protocol version 7, the
    /// resulting stream will always be empty.
    pub async fn get_cooldown_accounts(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<AccountPending, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_cooldown_accounts(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(pending) => pending.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get all accounts that have stake in pre-cooldown.
    /// (This only identifies accounts by index.)
    /// Prior to protocol version 7, the resulting stream will always be empty.
    pub async fn get_pre_cooldown_accounts(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<AccountIndex, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_pre_cooldown_accounts(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(account) => Ok(account.into()),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get all accounts that have stake in pre-pre-cooldown.
    /// (This only identifies accounts by index.)
    /// Prior to protocol version 7, the resulting stream will always be empty.
    pub async fn get_pre_pre_cooldown_accounts(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<AccountIndex, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_pre_pre_cooldown_accounts(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(account) => Ok(account.into()),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Get the chain parameters in effect after a given block.
    /// If the block does not exist [`QueryError::NotFound`] is returned.
    pub async fn get_block_chain_parameters(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<ChainParameters>> {
        let response = self
            .client
            .get_block_chain_parameters(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = ChainParameters::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// For a non-genesis block, this returns the
    /// [`QuorumCertificate`](block_certificates::QuorumCertificate), a
    /// [`TimeoutCertificate`](block_certificates::TimeoutCertificate) (if
    /// present)
    /// and [`EpochFinalizationEntry`](block_certificates::EpochFinalizationEntry) (if
    /// present).
    /// If the block being pointed to is *not* from protocol version 6 or
    /// above, then [`InvalidArgument`](`tonic::Code::InvalidArgument`)
    /// is returned.
    pub async fn get_block_certificates(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<block_certificates::BlockCertificates>> {
        let response = self
            .client
            .get_block_certificates(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = block_certificates::BlockCertificates::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get the information about a finalization record in a block.
    /// A block can contain zero or one finalization record. If a record is
    /// contained then this query will return information about the finalization
    /// session that produced it, including the finalizers eligible for the
    /// session, their power, and whether they signed this particular record. If
    /// the block does not exist [`QueryError::NotFound`] is returned.
    pub async fn get_block_finalization_summary(
        &mut self,
        block_id: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<Option<types::FinalizationSummary>>> {
        let response = self
            .client
            .get_block_finalization_summary(&block_id.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let response = response.into_inner().try_into()?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }

    /// Get a continous stream of finalized blocks starting from a given height.
    /// This function starts a background task (a `tokio` task) that listens for
    /// new finalized blocks. This task is killed when the
    /// [`FinalizedBlocksStream`] is dropped.
    pub async fn get_finalized_blocks_from(
        &mut self,
        start_height: AbsoluteBlockHeight,
    ) -> endpoints::QueryResult<FinalizedBlocksStream> {
        let mut fin_height = self.get_consensus_info().await?.last_finalized_block_height;
        let (sender, receiver) = tokio::sync::mpsc::channel(100);
        let mut client = self.clone();
        let handle = tokio::spawn(async move {
            let mut height = start_height;
            loop {
                if height > fin_height {
                    fin_height = client
                        .get_consensus_info()
                        .await?
                        .last_finalized_block_height;
                    if height > fin_height {
                        break;
                    }
                } else {
                    let mut bi = client.get_blocks_at_height(&height.into()).await?;
                    let block_hash = bi.pop().ok_or(endpoints::QueryError::NotFound)?;
                    let info = FinalizedBlockInfo { block_hash, height };
                    if sender.send(info).await.is_err() {
                        return Ok(());
                    }
                    height = height.next();
                }
            }
            let mut stream = client.get_finalized_blocks().await?;
            while let Some(fbi) = stream.next().await.transpose()? {
                // recover missed blocks.
                while height < fbi.height {
                    let mut bi = client.get_blocks_at_height(&height.into()).await?;
                    let block_hash = bi.pop().ok_or(endpoints::QueryError::NotFound)?;
                    let info = FinalizedBlockInfo { block_hash, height };
                    if sender.send(info).await.is_err() {
                        return Ok(());
                    }
                    height = height.next();
                }
                if sender.send(fbi).await.is_err() {
                    return Ok(());
                }
                height = height.next();
            }
            Ok(())
        });
        Ok(FinalizedBlocksStream { handle, receiver })
    }

    /// Find a block in which the account was created, if it exists and is
    /// finalized. The return value is a triple of the absolute block height and
    /// the corresponding block hash, and the account information at the
    /// end of that block. The block is the first block in which the account
    /// appears.
    ///
    /// Note that this is not necessarily the initial state of the account
    /// since there can be transactions updating it in the same block that it is
    /// created.
    ///
    /// Optional bounds can be provided, and the search will only
    /// consider blocks in that range. If the lower bound is not
    /// provided it defaults to 0, if the upper bound is not provided it
    /// defaults to the last finalized block at the time of the call.
    ///
    /// If the account cannot be found [`QueryError::NotFound`] is returned.
    pub async fn find_account_creation(
        &mut self,
        range: impl std::ops::RangeBounds<AbsoluteBlockHeight>,
        addr: AccountAddress,
    ) -> QueryResult<(AbsoluteBlockHeight, BlockHash, AccountInfo)> {
        self.find_at_lowest_height(range, |mut client, height| async move {
            match client.get_account_info(&addr.into(), &height).await {
                Ok(ii) => Ok(Some((height, ii.block_hash, ii.response))),
                Err(e) if e.is_not_found() => Ok(None),
                Err(e) => Err(e),
            }
        })
        .await
    }

    /// Find a block in which the instance was created, if it exists and is
    /// finalized. The return value is a triple of the absolute block height and
    /// the corresponding block hash, and the instance information at the
    /// end of that block. The block is the first block in which the instance
    /// appears.
    ///
    /// Note that this is not necessarily the initial state of the instance
    /// since there can be transactions updating the instance in the same block
    /// as the initialization transaction.
    ///
    /// Optional bounds can be provided, and the search will only
    /// consider blocks in that range. If the lower bound is not
    /// provided it defaults to 0, if the upper bound is not provided it
    /// defaults to the last finalized block at the time of the call.
    ///
    /// If the instance cannot be found [`QueryError::NotFound`] is returned.
    pub async fn find_instance_creation(
        &mut self,
        range: impl std::ops::RangeBounds<AbsoluteBlockHeight>,
        addr: ContractAddress,
    ) -> QueryResult<(AbsoluteBlockHeight, BlockHash, InstanceInfo)> {
        self.find_at_lowest_height(range, |mut client, height| async move {
            match client.get_instance_info(addr, &height).await {
                Ok(ii) => Ok(Some((height, ii.block_hash, ii.response))),
                Err(e) if e.is_not_found() => Ok(None),
                Err(e) => Err(e),
            }
        })
        .await
    }

    /// Find the first (i.e., earliest) finalized block whose slot time is no
    /// earlier than the specified time. If a block is not found return
    /// [`QueryError::NotFound`].
    ///
    /// The search is limited to the bounds specified. If the lower bound is not
    /// provided it defaults to 0, if the upper bound is not provided it
    /// defaults to the last finalized block at the time of the call.
    pub async fn find_first_finalized_block_no_earlier_than(
        &mut self,
        range: impl std::ops::RangeBounds<AbsoluteBlockHeight>,
        time: chrono::DateTime<chrono::Utc>,
    ) -> QueryResult<types::queries::BlockInfo> {
        self.find_at_lowest_height(range, move |mut client, height| async move {
            let info = client.get_block_info(&height).await?.response;
            if info.block_slot_time >= time {
                Ok(Some(info))
            } else {
                Ok(None)
            }
        })
        .await
    }

    /// Find a **finalized** block with lowest height that satisfies the given
    /// condition. If a block is not found return [`QueryError::NotFound`].
    ///
    /// The `test` method should return `Some` if the object is found in the
    /// block, and `None` otherwise. It can also signal errors which will
    /// terminate search immediately.
    ///
    /// The precondition for this method is that the `test` method is monotone,
    /// i.e., if block at height `h` satisfies the test then also a block at
    /// height `h+1` does.
    /// If this precondition does not hold then the return value from this
    /// method is unspecified.
    ///
    /// The search is limited to at most the given range, the upper bound is
    /// always at most the last finalized block at the time of the call. If the
    /// lower bound is not provided it defaults to 0, if the upper bound is
    /// not provided it defaults to the last finalized block at the time of
    /// the call.
    pub async fn find_at_lowest_height<A, F: futures::Future<Output = QueryResult<Option<A>>>>(
        &mut self,
        range: impl std::ops::RangeBounds<AbsoluteBlockHeight>,
        test: impl Fn(Self, AbsoluteBlockHeight) -> F,
    ) -> QueryResult<A> {
        let mut start = match range.start_bound() {
            std::ops::Bound::Included(s) => u64::from(*s),
            std::ops::Bound::Excluded(e) => u64::from(*e).saturating_add(1),
            std::ops::Bound::Unbounded => 0,
        };
        let mut end = {
            let ci = self.get_consensus_info().await?;
            let bound = |end: u64| std::cmp::min(end, ci.last_finalized_block_height.into());
            match range.end_bound() {
                std::ops::Bound::Included(e) => bound(u64::from(*e)),
                std::ops::Bound::Excluded(e) => {
                    bound(u64::from(*e).checked_sub(1).ok_or(QueryError::NotFound)?)
                }
                std::ops::Bound::Unbounded => u64::from(ci.last_finalized_block_height),
            }
        };
        if end < start {
            return Err(QueryError::NotFound);
        }
        let mut last_found = None;
        while start < end {
            let mid = start + (end - start) / 2;
            let ok = test(self.clone(), mid.into()).await?;
            if ok.is_some() {
                end = mid;
                last_found = ok;
            } else {
                start = mid + 1;
            }
        }
        last_found.ok_or(QueryError::NotFound)
    }

    #[deprecated(note = "Use [`find_at_lowest_height`](./struct.Client.html#method.\
                         find_at_lowest_height) instead since it avoids an extra call.")]
    pub async fn find_earliest_finalized<A, F: futures::Future<Output = QueryResult<Option<A>>>>(
        &mut self,
        range: impl std::ops::RangeBounds<AbsoluteBlockHeight>,
        test: impl Fn(Self, AbsoluteBlockHeight, BlockHash) -> F,
    ) -> QueryResult<A> {
        let mut start = match range.start_bound() {
            std::ops::Bound::Included(s) => u64::from(*s),
            std::ops::Bound::Excluded(e) => u64::from(*e).saturating_add(1),
            std::ops::Bound::Unbounded => 0,
        };
        let mut end = {
            let ci = self.get_consensus_info().await?;
            let bound = |end: u64| std::cmp::min(end, ci.last_finalized_block_height.into());
            match range.end_bound() {
                std::ops::Bound::Included(e) => bound(u64::from(*e)),
                std::ops::Bound::Excluded(e) => {
                    bound(u64::from(*e).checked_sub(1).ok_or(QueryError::NotFound)?)
                }
                std::ops::Bound::Unbounded => u64::from(ci.last_finalized_block_height),
            }
        };
        if end < start {
            return Err(QueryError::NotFound);
        }
        let mut last_found = None;
        while start < end {
            let mid = start + (end - start) / 2;
            let bh = self
                .get_blocks_at_height(&AbsoluteBlockHeight::from(mid).into())
                .await?[0]; // using [0] is safe since we are only looking at finalized blocks.
            let ok = test(self.clone(), mid.into(), bh).await?;
            if ok.is_some() {
                end = mid;
                last_found = ok;
            } else {
                start = mid + 1;
            }
        }
        last_found.ok_or(QueryError::NotFound)
    }

    /// Get all bakers in the reward period of a block.
    /// This endpoint is only supported for protocol version 4 and onwards.
    /// If the protocol does not support the endpoint then an
    /// [`IllegalArgument`](tonic::Code::InvalidArgument) is returned.
    pub async fn get_bakers_reward_period(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<types::BakerRewardPeriodInfo, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_bakers_reward_period(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(baker) => baker.try_into(),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Retrieve the list of protocol level tokens that exist at the end of the
    /// given block.
    ///
    /// This endpoint is only relevant starting from Concordium Protocol Version
    /// 9 and onwards.
    pub async fn get_token_list(
        &mut self,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<
        QueryResponse<impl Stream<Item = Result<protocol_level_tokens::TokenId, tonic::Status>>>,
    > {
        let response = self
            .client
            .get_token_list(&bi.into_block_identifier())
            .await?;
        let block_hash = extract_metadata(&response)?;
        let stream = response.into_inner().map(|result| match result {
            Ok(token_id) => protocol_level_tokens::TokenId::try_from(token_id),
            Err(err) => Err(err),
        });
        Ok(QueryResponse {
            block_hash,
            response: stream,
        })
    }

    /// Retrieve the information about the given protocol level token in the
    /// given block.
    ///
    /// This endpoint is only relevant starting from Concordium Protocol Version
    /// 9 and onwards.
    pub async fn get_token_info(
        &mut self,
        token_id: protocol_level_tokens::TokenId,
        bi: impl IntoBlockIdentifier,
    ) -> endpoints::QueryResult<QueryResponse<protocol_level_tokens::TokenInfo>> {
        let request = generated::TokenInfoRequest {
            block_hash: Some((&bi.into_block_identifier()).into()),
            token_id: Some(token_id.into()),
        };
        let response = self.client.get_token_info(request).await?;
        let block_hash = extract_metadata(&response)?;
        let response = protocol_level_tokens::TokenInfo::try_from(response.into_inner())?;
        Ok(QueryResponse {
            block_hash,
            response,
        })
    }
}

/// A stream of finalized blocks. This contains a background task that polls
/// for new finalized blocks indefinitely. The task can be stopped by dropping
/// the object.
pub struct FinalizedBlocksStream {
    handle: tokio::task::JoinHandle<endpoints::QueryResult<()>>,
    receiver: tokio::sync::mpsc::Receiver<FinalizedBlockInfo>,
}

// Make sure to abort the background task so that those resources are cleaned up
// before we drop the handle.
impl Drop for FinalizedBlocksStream {
    fn drop(&mut self) {
        self.handle.abort();
    }
}

impl FinalizedBlocksStream {
    /// Retrieves the next finalized block from the stream. This function will
    /// block until a finalized block becomes available. To avoid waiting
    /// indefinitely, consider using [`FinalizedBlocksStream::next_timeout`]
    /// instead. If the channel is closed, the next element is `None`.
    pub async fn next(&mut self) -> Option<FinalizedBlockInfo> {
        self.receiver.recv().await
    }

    /// Similar to [`FinalizedBlocksStream::next`], but with a maximum wait time
    /// defined by the specified duration between each finalized block.
    pub async fn next_timeout(
        &mut self,
        duration: std::time::Duration,
    ) -> Result<Option<FinalizedBlockInfo>, tokio::time::error::Elapsed> {
        tokio::time::timeout(duration, async move { self.next().await }).await
    }

    /// Get the next chunk of blocks. If the finalized block poller has been
    /// disconnected this will return `Err(blocks)` where `blocks` are the
    /// finalized blocks that were retrieved before closure. In that case
    /// all further calls will return `Err(Vec::new())`.
    ///
    /// In case of success up to `max(1, n)` elements will be returned. This
    /// function will block so it always returns at least one element, and
    /// will retrieve up to `n` elements without blocking further once at least
    /// one element has been acquired.
    pub async fn next_chunk(
        &mut self,
        n: usize,
    ) -> Result<Vec<FinalizedBlockInfo>, Vec<FinalizedBlockInfo>> {
        let mut out = Vec::with_capacity(n);
        let first = self.receiver.recv().await;
        match first {
            Some(v) => out.push(v),
            None => {
                return Err(out);
            }
        }
        for _ in 1..n {
            match self.receiver.try_recv() {
                Ok(v) => {
                    out.push(v);
                }
                Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
                    break;
                }
                Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => return Err(out),
            }
        }
        Ok(out)
    }

    /// Like [`next_chunk`](Self::next_chunk), but waits no more than the given
    /// duration for the block. The boolean signifies whether an error
    /// occurred (it is `true` if an error occurred) while getting blocks.
    /// If that is the case further calls will always yield an error.
    ///
    /// The first field of the response indicates if an error occurred. This
    /// will only happen if the stream of finalized blocks has unexpectedly
    /// dropped.
    pub async fn next_chunk_timeout(
        &mut self,
        n: usize,
        duration: std::time::Duration,
    ) -> Result<(bool, Vec<FinalizedBlockInfo>), tokio::time::error::Elapsed> {
        let mut out = Vec::with_capacity(n);
        let first = self.next_timeout(duration).await?;
        match first {
            Some(v) => out.push(v),
            None => return Ok((true, out)),
        }
        for _ in 1..n {
            match self.receiver.try_recv() {
                Ok(v) => {
                    out.push(v);
                }
                Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
                    break;
                }
                Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
                    return Ok((true, out))
                }
            }
        }
        Ok((false, out))
    }
}

fn extract_metadata<T>(response: &tonic::Response<T>) -> endpoints::RPCResult<BlockHash> {
    match response.metadata().get("blockhash") {
        Some(bytes) => {
            let bytes = bytes.as_bytes();
            if bytes.len() == 64 {
                let mut hash = [0u8; 32];
                if hex::decode_to_slice(bytes, &mut hash).is_err() {
                    tonic::Status::unknown("Response does correctly encode the block hash.");
                }
                Ok(hash.into())
            } else {
                Err(endpoints::RPCError::CallError(tonic::Status::unknown(
                    "Response does not include the expected metadata.",
                )))
            }
        }
        None => Err(endpoints::RPCError::CallError(tonic::Status::unknown(
            "Response does not include the expected metadata.",
        ))),
    }
}

/// A helper trait to make it simpler to require specific fields when parsing a
/// protobuf message by allowing us to use method calling syntax and
/// constructing responses that match the calling context, allowing us to use
/// the `?` syntax.
///
/// The main reason for needing this is that in proto3 all fields are optional,
/// so it is up to the application to validate inputs if they are required.
pub(crate) trait Require<E> {
    type A;
    fn require(self) -> Result<Self::A, E>;
}

impl<A> Require<tonic::Status> for Option<A> {
    type A = A;

    fn require(self) -> Result<Self::A, tonic::Status> {
        match self {
            Some(v) => Ok(v),
            None => Err(tonic::Status::invalid_argument("missing field in response")),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    /// Test the different cases when parsing BlockIdentifiers.
    fn block_ident_from_str() -> anyhow::Result<()> {
        let b1 = "best".parse::<BlockIdentifier>()?;
        assert_eq!(b1, BlockIdentifier::Best);

        let b2 = "lastFinal".parse::<BlockIdentifier>()?;
        assert_eq!(b2, BlockIdentifier::LastFinal);

        let b3 = "lastfinal".parse::<BlockIdentifier>()?;
        assert_eq!(b3, BlockIdentifier::LastFinal);

        let b4 = "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"
            .parse::<BlockIdentifier>()?;
        assert_eq!(
            b4,
            BlockIdentifier::Given(
                "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff".parse()?
            )
        );

        let b5 = "@33".parse::<BlockIdentifier>()?;
        assert_eq!(b5, BlockIdentifier::AbsoluteHeight(33.into()));

        let b6 = "@33/3".parse::<BlockIdentifier>()?;
        assert_eq!(
            b6,
            BlockIdentifier::RelativeHeight(RelativeBlockHeight {
                genesis_index: 3.into(),
                height: 33.into(),
                restrict: false,
            })
        );

        let b7 = "@33/3!".parse::<BlockIdentifier>()?;
        assert_eq!(
            b7,
            BlockIdentifier::RelativeHeight(RelativeBlockHeight {
                genesis_index: 3.into(),
                height: 33.into(),
                restrict: true,
            })
        );

        Ok(())
    }
}