1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
//! Proposal  Account

use {
    crate::{
        addins::max_voter_weight::{
            assert_is_valid_max_voter_weight,
            get_max_voter_weight_record_data_for_realm_and_governing_token_mint,
        },
        error::GovernanceError,
        state::{
            enums::{
                GovernanceAccountType, InstructionExecutionFlags, MintMaxVoterWeightSource,
                ProposalState, TransactionExecutionStatus, VoteThreshold, VoteTipping,
            },
            governance::GovernanceConfig,
            legacy::ProposalV1,
            proposal_transaction::ProposalTransactionV2,
            realm::RealmV2,
            realm_config::RealmConfigAccount,
            vote_record::{Vote, VoteKind},
        },
        tools::spl_token::get_spl_token_mint_supply,
        PROGRAM_AUTHORITY_SEED,
    },
    borsh::{maybestd::io::Write, BorshDeserialize, BorshSchema, BorshSerialize},
    solana_program::{
        account_info::{next_account_info, AccountInfo},
        clock::{Slot, UnixTimestamp},
        program_error::ProgramError,
        program_pack::IsInitialized,
        pubkey::Pubkey,
    },
    spl_governance_tools::account::{get_account_data, get_account_type, AccountMaxSize},
    std::{cmp::Ordering, slice::Iter},
};

/// Proposal option vote result
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub enum OptionVoteResult {
    /// Vote on the option is not resolved yet
    None,

    /// Vote on the option is completed and the option passed
    Succeeded,

    /// Vote on the option is completed and the option was defeated
    Defeated,
}

/// Proposal Option
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct ProposalOption {
    /// Option label
    pub label: String,

    /// Vote weight for the option
    pub vote_weight: u64,

    /// Vote result for the option
    pub vote_result: OptionVoteResult,

    /// The number of the transactions already executed
    pub transactions_executed_count: u16,

    /// The number of transactions included in the option
    pub transactions_count: u16,

    /// The index of the the next transaction to be added
    pub transactions_next_index: u16,
}

/// Proposal vote type
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub enum VoteType {
    /// Single choice vote with mutually exclusive choices
    /// In the SingeChoice mode there can ever be a single winner
    /// If multiple options score the same highest vote then the Proposal is
    /// not resolved and considered as Failed.
    /// Note: Yes/No vote is a single choice (Yes) vote with the deny
    /// option (No)
    SingleChoice,

    /// Multiple options can be selected with up to max_voter_options per voter
    /// and with up to max_winning_options of successful options
    /// Ex. voters are given 5 options, can choose up to 3 (max_voter_options)
    /// and only 1 (max_winning_options) option can win and be executed
    MultiChoice {
        /// Type of MultiChoice
        #[allow(dead_code)]
        choice_type: MultiChoiceType,

        /// The min number of options a voter must choose
        ///
        /// Note: In the current version the limit is not supported and not
        /// enforced and must always be set to 1
        #[allow(dead_code)]
        min_voter_options: u8,

        /// The max number of options a voter can choose
        ///
        /// Note: In the current version the limit is not supported and not
        /// enforced and must always be set to the number of available
        /// options
        #[allow(dead_code)]
        max_voter_options: u8,

        /// The max number of wining options
        /// For executable proposals it limits how many options can be executed
        /// for a Proposal
        ///
        /// Note: In the current version the limit is not supported and not
        /// enforced and must always be set to the number of available
        /// options
        #[allow(dead_code)]
        max_winning_options: u8,
    },
}

/// Type of MultiChoice.
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub enum MultiChoiceType {
    /// Multiple options can be approved with full weight allocated to each
    /// approved option
    FullWeight,

    /// Multiple options can be approved with weight allocated proportionally
    /// to the percentage of the total weight.
    /// The full weight has to be voted among the approved options, i.e.,
    /// 100% of the weight has to be allocated
    Weighted,
}

/// Governance Proposal
#[derive(Clone, Debug, PartialEq, Eq, BorshDeserialize, BorshSerialize, BorshSchema)]
pub struct ProposalV2 {
    /// Governance account type
    pub account_type: GovernanceAccountType,

    /// Governance account the Proposal belongs to
    pub governance: Pubkey,

    /// Indicates which Governing Token is used to vote on the Proposal
    /// Whether the general Community token owners or the Council tokens owners
    /// vote on this Proposal
    pub governing_token_mint: Pubkey,

    /// Current proposal state
    pub state: ProposalState,

    // TODO: add state_at timestamp to have single field to filter recent proposals in the UI
    /// The TokenOwnerRecord representing the user who created and owns this
    /// Proposal
    pub token_owner_record: Pubkey,

    /// The number of signatories assigned to the Proposal
    pub signatories_count: u8,

    /// The number of signatories who already signed
    pub signatories_signed_off_count: u8,

    /// Vote type
    pub vote_type: VoteType,

    /// Proposal options
    pub options: Vec<ProposalOption>,

    /// The total weight of the Proposal rejection votes
    /// If the proposal has no deny option then the weight is None
    ///
    /// Only proposals with the deny option can have executable instructions
    /// attached to them Without the deny option a proposal is only non
    /// executable survey
    ///
    /// The deny options is also used for off-chain and/or manually executable
    /// proposal to make them binding as opposed to survey only proposals
    pub deny_vote_weight: Option<u64>,

    /// Reserved space for future versions
    /// This field is a leftover from unused veto_vote_weight: Option<u64>
    pub reserved1: u8,

    /// The total weight of  votes
    /// Note: Abstain is not supported in the current version
    pub abstain_vote_weight: Option<u64>,

    /// Optional start time if the Proposal should not enter voting state
    /// immediately after being signed off Note: start_at is not supported
    /// in the current version
    pub start_voting_at: Option<UnixTimestamp>,

    /// When the Proposal was created and entered Draft state
    pub draft_at: UnixTimestamp,

    /// When Signatories started signing off the Proposal
    pub signing_off_at: Option<UnixTimestamp>,

    /// When the Proposal began voting as UnixTimestamp
    pub voting_at: Option<UnixTimestamp>,

    /// When the Proposal began voting as Slot
    /// Note: The slot is not currently used but the exact slot is going to be
    /// required to support snapshot based vote weights
    pub voting_at_slot: Option<Slot>,

    /// When the Proposal ended voting and entered either Succeeded or Defeated
    pub voting_completed_at: Option<UnixTimestamp>,

    /// When the Proposal entered Executing state
    pub executing_at: Option<UnixTimestamp>,

    /// When the Proposal entered final state Completed or Cancelled and was
    /// closed
    pub closed_at: Option<UnixTimestamp>,

    /// Instruction execution flag for ordered and transactional instructions
    /// Note: This field is not used in the current version
    pub execution_flags: InstructionExecutionFlags,

    /// The max vote weight for the Governing Token mint at the time Proposal
    /// was decided.
    /// It's used to show correct vote results for historical proposals in
    /// cases when the mint supply or max weight source changed after vote was
    /// completed.
    pub max_vote_weight: Option<u64>,

    /// Max voting time for the proposal if different from parent Governance
    /// (only higher value possible).
    /// Note: This field is not used in the current version
    pub max_voting_time: Option<u32>,

    /// The vote threshold at the time Proposal was decided
    /// It's used to show correct vote results for historical proposals in cases
    /// when the threshold was changed for governance config after vote was
    /// completed.
    /// TODO: Use this field to override the threshold from parent Governance
    /// (only higher value possible)
    pub vote_threshold: Option<VoteThreshold>,

    /// Reserved space for future versions
    pub reserved: [u8; 64],

    /// Proposal name
    pub name: String,

    /// Link to proposal's description
    pub description_link: String,

    /// The total weight of Veto votes
    pub veto_vote_weight: u64,
}

impl AccountMaxSize for ProposalV2 {
    fn get_max_size(&self) -> Option<usize> {
        let options_size: usize = self.options.iter().map(|o| o.label.len() + 19).sum();
        Some(self.name.len() + self.description_link.len() + options_size + 297)
    }
}

impl IsInitialized for ProposalV2 {
    fn is_initialized(&self) -> bool {
        self.account_type == GovernanceAccountType::ProposalV2
    }
}

impl ProposalV2 {
    /// Checks if Signatories can be edited (added or removed) for the Proposal
    /// in the given state
    pub fn assert_can_edit_signatories(&self) -> Result<(), ProgramError> {
        self.assert_is_draft_state()
            .map_err(|_| GovernanceError::InvalidStateCannotEditSignatories.into())
    }

    /// Checks if Proposal can be singed off
    pub fn assert_can_sign_off(&self) -> Result<(), ProgramError> {
        match self.state {
            ProposalState::Draft | ProposalState::SigningOff => Ok(()),
            ProposalState::Executing
            | ProposalState::ExecutingWithErrors
            | ProposalState::Completed
            | ProposalState::Cancelled
            | ProposalState::Voting
            | ProposalState::Succeeded
            | ProposalState::Defeated
            | ProposalState::Vetoed => Err(GovernanceError::InvalidStateCannotSignOff.into()),
        }
    }

    /// Checks the Proposal is in Voting state
    fn assert_is_voting_state(&self) -> Result<(), ProgramError> {
        if self.state != ProposalState::Voting {
            return Err(GovernanceError::InvalidProposalState.into());
        }

        Ok(())
    }

    /// Checks the Proposal is in Draft state
    fn assert_is_draft_state(&self) -> Result<(), ProgramError> {
        if self.state != ProposalState::Draft {
            return Err(GovernanceError::InvalidProposalState.into());
        }

        Ok(())
    }

    /// Checks the Proposal was finalized (no more state transition will happen)
    pub fn assert_is_final_state(&self) -> Result<(), ProgramError> {
        match self.state {
            ProposalState::Completed
            | ProposalState::Cancelled
            | ProposalState::Defeated
            | ProposalState::Vetoed => Ok(()),
            ProposalState::Executing
            | ProposalState::ExecutingWithErrors
            | ProposalState::SigningOff
            | ProposalState::Voting
            | ProposalState::Draft
            | ProposalState::Succeeded => Err(GovernanceError::InvalidStateNotFinal.into()),
        }
    }

    /// Checks if Proposal can be voted on
    pub fn assert_can_cast_vote(
        &self,
        config: &GovernanceConfig,
        vote: &Vote,
        current_unix_timestamp: UnixTimestamp,
    ) -> Result<(), ProgramError> {
        self.assert_is_voting_state()
            .map_err(|_| GovernanceError::InvalidStateCannotVote)?;

        // Check if we are still within the configured max voting time period
        if self.has_voting_max_time_ended(config, current_unix_timestamp) {
            return Err(GovernanceError::ProposalVotingTimeExpired.into());
        }

        match vote {
            Vote::Approve(_) | Vote::Abstain => {
                // Once the base voting time passes and we are in the voting cool off time
                // approving votes are no longer accepted Abstain is considered
                // as positive vote because when attendance quorum is used it can tip the scales
                if self.has_voting_base_time_ended(config, current_unix_timestamp) {
                    Err(GovernanceError::VoteNotAllowedInCoolOffTime.into())
                } else {
                    Ok(())
                }
            }
            // Within voting cool off time only counter votes are allowed
            Vote::Deny | Vote::Veto => Ok(()),
        }
    }

    /// Checks if proposal has concluded so that security deposit is no longer
    /// needed
    pub fn assert_can_refund_proposal_deposit(&self) -> Result<(), ProgramError> {
        match self.state {
            ProposalState::Succeeded
            | ProposalState::Executing
            | ProposalState::Completed
            | ProposalState::Cancelled
            | ProposalState::Defeated
            | ProposalState::ExecutingWithErrors
            | ProposalState::Vetoed => Ok(()),
            ProposalState::Draft | ProposalState::SigningOff | ProposalState::Voting => {
                Err(GovernanceError::CannotRefundProposalDeposit.into())
            }
        }
    }

    /// Expected base vote end time determined by the configured
    /// base_voting_time and actual voting start time
    pub fn voting_base_time_end(&self, config: &GovernanceConfig) -> UnixTimestamp {
        self.voting_at
            .unwrap()
            .checked_add(config.voting_base_time as i64)
            .unwrap()
    }

    /// Checks whether the base voting time has ended for the proposal
    pub fn has_voting_base_time_ended(
        &self,
        config: &GovernanceConfig,
        current_unix_timestamp: UnixTimestamp,
    ) -> bool {
        // Check if we passed the configured base vote end time
        self.voting_base_time_end(config) < current_unix_timestamp
    }

    /// Expected max vote end time determined by the configured
    /// base_voting_time, optional voting_cool_off_time and actual voting start
    /// time
    pub fn voting_max_time_end(&self, config: &GovernanceConfig) -> UnixTimestamp {
        self.voting_base_time_end(config)
            .checked_add(config.voting_cool_off_time as i64)
            .unwrap()
    }

    /// Checks whether the max voting time has ended for the proposal
    pub fn has_voting_max_time_ended(
        &self,
        config: &GovernanceConfig,
        current_unix_timestamp: UnixTimestamp,
    ) -> bool {
        // Check if we passed the max vote end time
        self.voting_max_time_end(config) < current_unix_timestamp
    }

    /// Checks if Proposal can be finalized
    pub fn assert_can_finalize_vote(
        &self,
        config: &GovernanceConfig,
        current_unix_timestamp: UnixTimestamp,
    ) -> Result<(), ProgramError> {
        self.assert_is_voting_state()
            .map_err(|_| GovernanceError::InvalidStateCannotFinalize)?;

        // We can only finalize the vote after the configured max_voting_time has
        // expired and vote time ended
        if !self.has_voting_max_time_ended(config, current_unix_timestamp) {
            return Err(GovernanceError::CannotFinalizeVotingInProgress.into());
        }

        Ok(())
    }

    /// Finalizes vote by moving it to final state Succeeded or Defeated if
    /// max_voting_time has passed If Proposal is still within
    /// max_voting_time period then error is returned
    pub fn finalize_vote(
        &mut self,
        max_voter_weight: u64,
        config: &GovernanceConfig,
        current_unix_timestamp: UnixTimestamp,
        vote_threshold: &VoteThreshold,
    ) -> Result<(), ProgramError> {
        self.assert_can_finalize_vote(config, current_unix_timestamp)?;

        self.state = self.resolve_final_vote_state(max_voter_weight, vote_threshold)?;
        self.voting_completed_at = Some(self.voting_max_time_end(config));

        // Capture vote params to correctly display historical results
        self.max_vote_weight = Some(max_voter_weight);
        self.vote_threshold = Some(vote_threshold.clone());

        Ok(())
    }

    /// Resolves final proposal state after vote ends
    /// It inspects all proposals options and resolves their final vote results
    fn resolve_final_vote_state(
        &mut self,
        max_vote_weight: u64,
        vote_threshold: &VoteThreshold,
    ) -> Result<ProposalState, ProgramError> {
        // Get the min vote weight required for options to pass
        let min_vote_threshold_weight =
            get_min_vote_threshold_weight(vote_threshold, max_vote_weight).unwrap();

        // If the proposal has a reject option then any other option must beat it
        // regardless of the configured min_vote_threshold_weight
        let deny_vote_weight = self.deny_vote_weight.unwrap_or(0);

        let mut best_succeeded_option_weight = 0;
        let mut best_succeeded_option_count = 0u16;

        for option in self.options.iter_mut() {
            // Any positive vote (Yes) must be equal or above the required
            // min_vote_threshold_weight and higher than the reject option vote (No)
            // The same number of positive (Yes) and rejecting (No) votes is a tie and
            // resolved as Defeated In other words  +1 vote as a tie breaker is
            // required to succeed for the positive option vote
            if option.vote_weight >= min_vote_threshold_weight
                && option.vote_weight > deny_vote_weight
            {
                option.vote_result = OptionVoteResult::Succeeded;

                match option.vote_weight.cmp(&best_succeeded_option_weight) {
                    Ordering::Greater => {
                        best_succeeded_option_weight = option.vote_weight;
                        best_succeeded_option_count = 1;
                    }
                    Ordering::Equal => {
                        best_succeeded_option_count =
                            best_succeeded_option_count.checked_add(1).unwrap()
                    }
                    Ordering::Less => {}
                }
            } else {
                option.vote_result = OptionVoteResult::Defeated;
            }
        }

        let mut final_state = if best_succeeded_option_count == 0 {
            // If none of the individual options succeeded then the proposal as a whole is
            // defeated
            ProposalState::Defeated
        } else {
            match &self.vote_type {
                VoteType::SingleChoice => {
                    let proposal_state = if best_succeeded_option_count > 1 {
                        // If there is more than one winning option then the single choice proposal
                        // is considered as defeated
                        best_succeeded_option_weight = u64::MAX; // no winning option
                        ProposalState::Defeated
                    } else {
                        ProposalState::Succeeded
                    };

                    // Coerce options vote results based on the winning score
                    // (best_succeeded_vote_weight)
                    for option in self.options.iter_mut() {
                        option.vote_result = if option.vote_weight == best_succeeded_option_weight {
                            OptionVoteResult::Succeeded
                        } else {
                            OptionVoteResult::Defeated
                        };
                    }

                    proposal_state
                }
                VoteType::MultiChoice {
                    choice_type: _,
                    max_voter_options: _,
                    max_winning_options: _,
                    min_voter_options: _,
                } => {
                    // If any option succeeded for multi choice then the proposal as a whole
                    // succeeded as well
                    ProposalState::Succeeded
                }
            }
        };

        // None executable proposal is just a survey and is considered Completed once
        // the vote ends and no more actions are available There is no overall
        // Success or Failure status for the Proposal however individual options still
        // have their own status
        //
        // Note: An off-chain/manually executable Proposal has no instructions but it
        // still must have the deny vote enabled to be binding In such a case,
        // if successful, the Proposal vote ends in Succeeded state and it must be
        // manually transitioned to Completed state by the Proposal owner once
        // the external actions are executed
        if self.deny_vote_weight.is_none() {
            final_state = ProposalState::Completed;
        }

        Ok(final_state)
    }

    /// Calculates max voter weight for given mint supply and realm config
    fn get_max_voter_weight_from_mint_supply(
        &mut self,
        realm_data: &RealmV2,
        governing_token_mint: &Pubkey,
        governing_token_mint_supply: u64,
        vote_kind: &VoteKind,
    ) -> Result<u64, ProgramError> {
        // max vote weight fraction is only used for community mint
        if Some(*governing_token_mint) == realm_data.config.council_mint {
            return Ok(governing_token_mint_supply);
        }

        let max_voter_weight = match realm_data.config.community_mint_max_voter_weight_source {
            MintMaxVoterWeightSource::SupplyFraction(fraction) => {
                if fraction == MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE {
                    return Ok(governing_token_mint_supply);
                }

                (governing_token_mint_supply as u128)
                    .checked_mul(fraction as u128)
                    .unwrap()
                    .checked_div(MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE as u128)
                    .unwrap() as u64
            }
            MintMaxVoterWeightSource::Absolute(value) => value,
        };

        // When the fraction or absolute value is used it's possible we can go over the
        // calculated max_vote_weight and we have to adjust it in case more
        // votes have been cast
        Ok(self.coerce_max_voter_weight(max_voter_weight, vote_kind))
    }

    /// Adjusts max voter weight to ensure it's not lower than total cast votes
    fn coerce_max_voter_weight(&self, max_voter_weight: u64, vote_kind: &VoteKind) -> u64 {
        let total_vote_weight = match vote_kind {
            VoteKind::Electorate => {
                let deny_vote_weight = self.deny_vote_weight.unwrap_or(0);

                let max_option_vote_weight =
                    self.options.iter().map(|o| o.vote_weight).max().unwrap();

                max_option_vote_weight
                    .checked_add(deny_vote_weight)
                    .unwrap()
            }
            VoteKind::Veto => self.veto_vote_weight,
        };

        max_voter_weight.max(total_vote_weight)
    }

    /// Resolves max voter weight using either 1) voting governing_token_mint
    /// supply or 2) max voter weight if configured for the token mint
    #[allow(clippy::too_many_arguments)]
    pub fn resolve_max_voter_weight(
        &mut self,
        account_info_iter: &mut Iter<AccountInfo>,
        realm: &Pubkey,
        realm_data: &RealmV2,
        realm_config_data: &RealmConfigAccount,
        vote_governing_token_mint_info: &AccountInfo,
        vote_kind: &VoteKind,
    ) -> Result<u64, ProgramError> {
        // if the Realm is configured to use max voter weight for the given voting
        // governing_token_mint then use the externally provided max_voter_weight
        // instead of the supply based max
        if let Some(max_voter_weight_addin) = realm_config_data
            .get_token_config(realm_data, vote_governing_token_mint_info.key)?
            .max_voter_weight_addin
        {
            let max_voter_weight_record_info = next_account_info(account_info_iter)?;

            let max_voter_weight_record_data =
                get_max_voter_weight_record_data_for_realm_and_governing_token_mint(
                    &max_voter_weight_addin,
                    max_voter_weight_record_info,
                    realm,
                    vote_governing_token_mint_info.key,
                )?;

            assert_is_valid_max_voter_weight(&max_voter_weight_record_data)?;

            // When the max voter weight addin is used it's possible it can be inaccurate
            // and we can have more votes then the max provided by the addin and
            // we have to adjust it to whatever result is higher
            return Ok(self.coerce_max_voter_weight(
                max_voter_weight_record_data.max_voter_weight,
                vote_kind,
            ));
        }

        let vote_governing_token_mint_supply =
            get_spl_token_mint_supply(vote_governing_token_mint_info)?;

        let max_voter_weight = self.get_max_voter_weight_from_mint_supply(
            realm_data,
            vote_governing_token_mint_info.key,
            vote_governing_token_mint_supply,
            vote_kind,
        )?;

        Ok(max_voter_weight)
    }

    /// Checks if vote can be tipped and automatically transitioned to Succeeded
    /// or Defeated state If the conditions are met the state is updated
    /// accordingly
    pub fn try_tip_vote(
        &mut self,
        max_voter_weight: u64,
        vote_tipping: &VoteTipping,
        current_unix_timestamp: UnixTimestamp,
        vote_threshold: &VoteThreshold,
        vote_kind: &VoteKind,
    ) -> Result<bool, ProgramError> {
        if let Some(tipped_state) = self.try_get_tipped_vote_state(
            max_voter_weight,
            vote_tipping,
            vote_threshold,
            vote_kind,
        ) {
            self.state = tipped_state;
            self.voting_completed_at = Some(current_unix_timestamp);

            // Capture vote params to correctly display historical results
            // Note: For Veto vote the captured params are from the Veto config
            self.max_vote_weight = Some(max_voter_weight);
            self.vote_threshold = Some(vote_threshold.clone());

            Ok(true)
        } else {
            Ok(false)
        }
    }

    /// Checks if vote can be tipped and automatically transitioned to
    /// Succeeded, Defeated or Vetoed state.
    /// If yes then Some(ProposalState) is returned and None otherwise
    pub fn try_get_tipped_vote_state(
        &mut self,
        max_voter_weight: u64,
        vote_tipping: &VoteTipping,
        vote_threshold: &VoteThreshold,
        vote_kind: &VoteKind,
    ) -> Option<ProposalState> {
        let min_vote_threshold_weight =
            get_min_vote_threshold_weight(vote_threshold, max_voter_weight).unwrap();

        match vote_kind {
            VoteKind::Electorate => self.try_get_tipped_electorate_vote_state(
                max_voter_weight,
                vote_tipping,
                min_vote_threshold_weight,
            ),
            VoteKind::Veto => self.try_get_tipped_veto_vote_state(min_vote_threshold_weight),
        }
    }

    /// Checks if Electorate vote can be tipped and automatically transitioned
    /// to Succeeded or Defeated state.
    /// If yes then Some(ProposalState) is returned and None otherwise
    fn try_get_tipped_electorate_vote_state(
        &mut self,
        max_voter_weight: u64,
        vote_tipping: &VoteTipping,
        min_vote_threshold_weight: u64,
    ) -> Option<ProposalState> {
        // Vote tipping is currently supported for SingleChoice votes with
        // single Yes and No (rejection) options only.
        // Note: Tipping for multiple options (single choice and multiple
        // choices) should be possible but it requires a great deal of
        // considerations and I decided to fight it another day
        if self.vote_type != VoteType::SingleChoice
            // Tipping should not be allowed for opinion only proposals (surveys
            // without rejection) to allow everybody's voice to be heard
            || self.deny_vote_weight.is_none()
            || self.options.len() != 1
        {
            return None;
        };

        let yes_option = &mut self.options[0];

        let yes_vote_weight = yes_option.vote_weight;
        let deny_vote_weight = self.deny_vote_weight.unwrap();

        match vote_tipping {
            VoteTipping::Disabled => {}
            VoteTipping::Strict => {
                if yes_vote_weight >= min_vote_threshold_weight
                    && yes_vote_weight > (max_voter_weight.saturating_sub(yes_vote_weight))
                {
                    yes_option.vote_result = OptionVoteResult::Succeeded;
                    return Some(ProposalState::Succeeded);
                }
            }
            VoteTipping::Early => {
                if yes_vote_weight >= min_vote_threshold_weight
                    && yes_vote_weight > deny_vote_weight
                {
                    yes_option.vote_result = OptionVoteResult::Succeeded;
                    return Some(ProposalState::Succeeded);
                }
            }
        }

        // If vote tipping isn't disabled entirely, allow a vote to complete as
        // "defeated" if there is no possible way of reaching majority or the
        // min_vote_threshold_weight for another option. This tipping is always
        // strict, there's no equivalent to "early" tipping for deny votes.
        if *vote_tipping != VoteTipping::Disabled
            && (deny_vote_weight > (max_voter_weight.saturating_sub(min_vote_threshold_weight))
                || deny_vote_weight >= (max_voter_weight.saturating_sub(deny_vote_weight)))
        {
            yes_option.vote_result = OptionVoteResult::Defeated;
            return Some(ProposalState::Defeated);
        }

        None
    }

    /// Checks if vote can be tipped and transitioned to Vetoed state
    /// If yes then Some(ProposalState::Vetoed) is returned and None otherwise
    fn try_get_tipped_veto_vote_state(
        &mut self,
        min_vote_threshold_weight: u64,
    ) -> Option<ProposalState> {
        // Veto vote tips as soon as the required threshold is reached
        // It's irrespectively of vote_tipping config because the outcome of the
        // Proposal can't change any longer after being vetoed
        if self.veto_vote_weight >= min_vote_threshold_weight {
            // Note: Since we don't tip multi option votes all options vote_result would
            // remain as None
            Some(ProposalState::Vetoed)
        } else {
            None
        }
    }

    /// Checks if Proposal can be canceled in the given state
    pub fn assert_can_cancel(
        &self,
        config: &GovernanceConfig,
        current_unix_timestamp: UnixTimestamp,
    ) -> Result<(), ProgramError> {
        match self.state {
            ProposalState::Draft | ProposalState::SigningOff => Ok(()),
            ProposalState::Voting => {
                // Note: If there is no tipping point the proposal can be still in Voting state
                // but already past the configured max_voting_time In that case
                // we treat the proposal as finalized and it's no longer allowed to be canceled
                if self.has_voting_max_time_ended(config, current_unix_timestamp) {
                    return Err(GovernanceError::ProposalVotingTimeExpired.into());
                }
                Ok(())
            }
            ProposalState::Executing
            | ProposalState::ExecutingWithErrors
            | ProposalState::Completed
            | ProposalState::Cancelled
            | ProposalState::Succeeded
            | ProposalState::Defeated
            | ProposalState::Vetoed => {
                Err(GovernanceError::InvalidStateCannotCancelProposal.into())
            }
        }
    }

    /// Checks if Instructions can be edited (inserted or removed) for the
    /// Proposal in the given state It also asserts whether the Proposal is
    /// executable (has the reject option)
    pub fn assert_can_edit_instructions(&self) -> Result<(), ProgramError> {
        if self.assert_is_draft_state().is_err() {
            return Err(GovernanceError::InvalidStateCannotEditTransactions.into());
        }

        // For security purposes only proposals with the reject option can have
        // executable instructions
        if self.deny_vote_weight.is_none() {
            return Err(GovernanceError::ProposalIsNotExecutable.into());
        }

        Ok(())
    }

    /// Checks if Instructions can be executed for the Proposal in the given
    /// state
    pub fn assert_can_execute_transaction(
        &self,
        proposal_transaction_data: &ProposalTransactionV2,
        current_unix_timestamp: UnixTimestamp,
    ) -> Result<(), ProgramError> {
        match self.state {
            ProposalState::Succeeded
            | ProposalState::Executing
            | ProposalState::ExecutingWithErrors => {}
            ProposalState::Draft
            | ProposalState::SigningOff
            | ProposalState::Completed
            | ProposalState::Voting
            | ProposalState::Cancelled
            | ProposalState::Defeated
            | ProposalState::Vetoed => {
                return Err(GovernanceError::InvalidStateCannotExecuteTransaction.into())
            }
        }

        if self.options[proposal_transaction_data.option_index as usize].vote_result
            != OptionVoteResult::Succeeded
        {
            return Err(GovernanceError::CannotExecuteDefeatedOption.into());
        }

        if self
            .voting_completed_at
            .unwrap()
            .checked_add(proposal_transaction_data.hold_up_time as i64)
            .unwrap()
            >= current_unix_timestamp
        {
            return Err(GovernanceError::CannotExecuteTransactionWithinHoldUpTime.into());
        }

        if proposal_transaction_data.executed_at.is_some() {
            return Err(GovernanceError::TransactionAlreadyExecuted.into());
        }

        Ok(())
    }

    /// Checks if the instruction can be flagged with error for the Proposal in
    /// the given state
    pub fn assert_can_flag_transaction_error(
        &self,
        proposal_transaction_data: &ProposalTransactionV2,
        current_unix_timestamp: UnixTimestamp,
    ) -> Result<(), ProgramError> {
        // Instruction can be flagged for error only when it's eligible for execution
        self.assert_can_execute_transaction(proposal_transaction_data, current_unix_timestamp)?;

        if proposal_transaction_data.execution_status == TransactionExecutionStatus::Error {
            return Err(GovernanceError::TransactionAlreadyFlaggedWithError.into());
        }

        Ok(())
    }

    /// Checks if Proposal with off-chain/manual actions can be transitioned to
    /// Completed
    pub fn assert_can_complete(&self) -> Result<(), ProgramError> {
        // Proposal vote must be successful
        if self.state != ProposalState::Succeeded {
            return Err(GovernanceError::InvalidStateToCompleteProposal.into());
        }

        // There must be no on-chain executable actions
        if self.options.iter().any(|o| o.transactions_count != 0) {
            return Err(GovernanceError::InvalidStateToCompleteProposal.into());
        }

        Ok(())
    }

    /// Asserts the given vote is valid for the proposal
    pub fn assert_valid_vote(&self, vote: &Vote) -> Result<(), ProgramError> {
        match vote {
            Vote::Approve(choices) => {
                if self.options.len() != choices.len() {
                    return Err(GovernanceError::InvalidNumberOfVoteChoices.into());
                }

                let mut choice_count = 0u16;
                let mut total_choice_weight_percentage = 0u8;

                for choice in choices {
                    if choice.rank > 0 {
                        return Err(GovernanceError::RankedVoteIsNotSupported.into());
                    }

                    if choice.weight_percentage > 0 {
                        choice_count = choice_count.checked_add(1).unwrap();

                        match self.vote_type {
                            VoteType::MultiChoice {
                                choice_type: MultiChoiceType::Weighted,
                                min_voter_options: _,
                                max_voter_options: _,
                                max_winning_options: _,
                            } => {
                                // Calculate the total percentage for all choices for weighted
                                // choice vote. The total must add up
                                // to exactly 100%
                                total_choice_weight_percentage = total_choice_weight_percentage
                                    .checked_add(choice.weight_percentage)
                                    .ok_or(GovernanceError::TotalVoteWeightMustBe100Percent)?;
                            }
                            _ => {
                                if choice.weight_percentage != 100 {
                                    return Err(
                                        GovernanceError::ChoiceWeightMustBe100Percent.into()
                                    );
                                }
                            }
                        }
                    }
                }

                match self.vote_type {
                    VoteType::SingleChoice => {
                        if choice_count != 1 {
                            return Err(GovernanceError::SingleChoiceOnlyIsAllowed.into());
                        }
                    }
                    VoteType::MultiChoice {
                        choice_type: MultiChoiceType::FullWeight,
                        min_voter_options: _,
                        max_voter_options: _,
                        max_winning_options: _,
                    } => {
                        if choice_count == 0 {
                            return Err(GovernanceError::AtLeastSingleChoiceIsRequired.into());
                        }
                    }
                    VoteType::MultiChoice {
                        choice_type: MultiChoiceType::Weighted,
                        min_voter_options: _,
                        max_voter_options: _,
                        max_winning_options: _,
                    } => {
                        if choice_count == 0 {
                            return Err(GovernanceError::AtLeastSingleChoiceIsRequired.into());
                        }
                        if total_choice_weight_percentage != 100 {
                            return Err(GovernanceError::TotalVoteWeightMustBe100Percent.into());
                        }
                    }
                }
            }
            Vote::Deny => {
                if self.deny_vote_weight.is_none() {
                    return Err(GovernanceError::DenyVoteIsNotAllowed.into());
                }
            }
            Vote::Abstain => {
                return Err(GovernanceError::NotSupportedVoteType.into());
            }
            Vote::Veto => {}
        }

        Ok(())
    }

    /// Serializes account into the target buffer
    pub fn serialize<W: Write>(self, writer: W) -> Result<(), ProgramError> {
        if self.account_type == GovernanceAccountType::ProposalV2 {
            borsh::to_writer(writer, &self)?
        } else if self.account_type == GovernanceAccountType::ProposalV1 {
            // V1 account can't be resized and we have to translate it back to the original
            // format

            if self.abstain_vote_weight.is_some() {
                panic!("ProposalV1 doesn't support Abstain vote")
            }

            if self.veto_vote_weight > 0 {
                panic!("ProposalV1 doesn't support Veto vote")
            }

            if self.start_voting_at.is_some() {
                panic!("ProposalV1 doesn't support start time")
            }

            if self.max_voting_time.is_some() {
                panic!("ProposalV1 doesn't support max voting time")
            }

            if self.options.len() != 1 {
                panic!("ProposalV1 doesn't support multiple options")
            }

            let proposal_data_v1 = ProposalV1 {
                account_type: self.account_type,
                governance: self.governance,
                governing_token_mint: self.governing_token_mint,
                state: self.state,
                token_owner_record: self.token_owner_record,
                signatories_count: self.signatories_count,
                signatories_signed_off_count: self.signatories_signed_off_count,
                yes_votes_count: self.options[0].vote_weight,
                no_votes_count: self.deny_vote_weight.unwrap(),
                instructions_executed_count: self.options[0].transactions_executed_count,
                instructions_count: self.options[0].transactions_count,
                instructions_next_index: self.options[0].transactions_next_index,
                draft_at: self.draft_at,
                signing_off_at: self.signing_off_at,
                voting_at: self.voting_at,
                voting_at_slot: self.voting_at_slot,
                voting_completed_at: self.voting_completed_at,
                executing_at: self.executing_at,
                closed_at: self.closed_at,
                execution_flags: self.execution_flags,
                max_vote_weight: self.max_vote_weight,
                vote_threshold: self.vote_threshold,
                name: self.name,
                description_link: self.description_link,
            };

            borsh::to_writer(writer, &proposal_data_v1)?
        }

        Ok(())
    }
}

/// Converts given vote threshold (ex. in percentages) to absolute vote weight
/// and returns the min weight required for a proposal option to pass
fn get_min_vote_threshold_weight(
    vote_threshold: &VoteThreshold,
    max_voter_weight: u64,
) -> Result<u64, ProgramError> {
    let yes_vote_threshold_percentage = match vote_threshold {
        VoteThreshold::YesVotePercentage(yes_vote_threshold_percentage) => {
            *yes_vote_threshold_percentage
        }
        _ => {
            return Err(GovernanceError::VoteThresholdTypeNotSupported.into());
        }
    };

    let numerator = (yes_vote_threshold_percentage as u128)
        .checked_mul(max_voter_weight as u128)
        .unwrap();

    let mut yes_vote_threshold = numerator.checked_div(100).unwrap();

    if yes_vote_threshold.checked_mul(100).unwrap() < numerator {
        yes_vote_threshold = yes_vote_threshold.checked_add(1).unwrap();
    }

    Ok(yes_vote_threshold as u64)
}

/// Deserializes Proposal account and checks owner program
pub fn get_proposal_data(
    program_id: &Pubkey,
    proposal_info: &AccountInfo,
) -> Result<ProposalV2, ProgramError> {
    let account_type: GovernanceAccountType = get_account_type(program_id, proposal_info)?;

    // If the account is V1 version then translate to V2
    if account_type == GovernanceAccountType::ProposalV1 {
        let proposal_data_v1 = get_account_data::<ProposalV1>(program_id, proposal_info)?;

        let vote_result = match proposal_data_v1.state {
            ProposalState::Draft
            | ProposalState::SigningOff
            | ProposalState::Voting
            | ProposalState::Cancelled => OptionVoteResult::None,
            ProposalState::Succeeded
            | ProposalState::Executing
            | ProposalState::ExecutingWithErrors
            | ProposalState::Completed => OptionVoteResult::Succeeded,
            ProposalState::Vetoed | ProposalState::Defeated => OptionVoteResult::None,
        };

        return Ok(ProposalV2 {
            account_type,
            governance: proposal_data_v1.governance,
            governing_token_mint: proposal_data_v1.governing_token_mint,
            state: proposal_data_v1.state,
            token_owner_record: proposal_data_v1.token_owner_record,
            signatories_count: proposal_data_v1.signatories_count,
            signatories_signed_off_count: proposal_data_v1.signatories_signed_off_count,
            vote_type: VoteType::SingleChoice,
            options: vec![ProposalOption {
                label: "Yes".to_string(),
                vote_weight: proposal_data_v1.yes_votes_count,
                vote_result,
                transactions_executed_count: proposal_data_v1.instructions_executed_count,
                transactions_count: proposal_data_v1.instructions_count,
                transactions_next_index: proposal_data_v1.instructions_next_index,
            }],
            deny_vote_weight: Some(proposal_data_v1.no_votes_count),
            veto_vote_weight: 0,
            abstain_vote_weight: None,
            start_voting_at: None,
            draft_at: proposal_data_v1.draft_at,
            signing_off_at: proposal_data_v1.signing_off_at,
            voting_at: proposal_data_v1.voting_at,
            voting_at_slot: proposal_data_v1.voting_at_slot,
            voting_completed_at: proposal_data_v1.voting_completed_at,
            executing_at: proposal_data_v1.executing_at,
            closed_at: proposal_data_v1.closed_at,
            execution_flags: proposal_data_v1.execution_flags,
            max_vote_weight: proposal_data_v1.max_vote_weight,
            max_voting_time: None,
            vote_threshold: proposal_data_v1.vote_threshold,
            name: proposal_data_v1.name,
            description_link: proposal_data_v1.description_link,
            reserved: [0; 64],
            reserved1: 0,
        });
    }

    get_account_data::<ProposalV2>(program_id, proposal_info)
}

/// Deserializes Proposal and validates it belongs to the given Governance and
/// governing_token_mint
pub fn get_proposal_data_for_governance_and_governing_mint(
    program_id: &Pubkey,
    proposal_info: &AccountInfo,
    governance: &Pubkey,
    governing_token_mint: &Pubkey,
) -> Result<ProposalV2, ProgramError> {
    let proposal_data = get_proposal_data_for_governance(program_id, proposal_info, governance)?;

    if proposal_data.governing_token_mint != *governing_token_mint {
        return Err(GovernanceError::InvalidGoverningMintForProposal.into());
    }

    Ok(proposal_data)
}

/// Deserializes Proposal and validates it belongs to the given Governance
pub fn get_proposal_data_for_governance(
    program_id: &Pubkey,
    proposal_info: &AccountInfo,
    governance: &Pubkey,
) -> Result<ProposalV2, ProgramError> {
    let proposal_data = get_proposal_data(program_id, proposal_info)?;

    if proposal_data.governance != *governance {
        return Err(GovernanceError::InvalidGovernanceForProposal.into());
    }

    Ok(proposal_data)
}

/// Returns Proposal PDA seeds
pub fn get_proposal_address_seeds<'a>(
    governance: &'a Pubkey,
    governing_token_mint: &'a Pubkey,
    proposal_seed: &'a Pubkey,
) -> [&'a [u8]; 4] {
    [
        PROGRAM_AUTHORITY_SEED,
        governance.as_ref(),
        governing_token_mint.as_ref(),
        proposal_seed.as_ref(),
    ]
}

/// Returns Proposal PDA address
pub fn get_proposal_address<'a>(
    program_id: &Pubkey,
    governance: &'a Pubkey,
    governing_token_mint: &'a Pubkey,
    proposal_seed: &'a Pubkey,
) -> Pubkey {
    Pubkey::find_program_address(
        &get_proposal_address_seeds(governance, governing_token_mint, proposal_seed),
        program_id,
    )
    .0
}

/// Assert options to create proposal are valid for the Proposal vote_type
pub fn assert_valid_proposal_options(
    options: &[String],
    vote_type: &VoteType,
) -> Result<(), ProgramError> {
    if options.is_empty() || options.len() > 10 {
        return Err(GovernanceError::InvalidProposalOptions.into());
    }

    if let VoteType::MultiChoice {
        choice_type: _,
        min_voter_options,
        max_voter_options,
        max_winning_options,
    } = vote_type
    {
        if options.len() == 1
            || *max_voter_options as usize != options.len()
            || *max_winning_options as usize != options.len()
            || *min_voter_options != 1
        {
            return Err(GovernanceError::InvalidMultiChoiceProposalParameters.into());
        }
    }

    // TODO: Check for duplicated option labels
    // The options are identified by index so it's ok for now

    if options.iter().any(|o| o.is_empty()) {
        return Err(GovernanceError::InvalidProposalOptions.into());
    }

    Ok(())
}

#[cfg(test)]
mod test {
    use {
        super::*,
        crate::state::{
            enums::{MintMaxVoterWeightSource, VoteThreshold},
            legacy::ProposalV1,
            realm::RealmConfig,
            vote_record::VoteChoice,
        },
        proptest::prelude::*,
        solana_program::clock::Epoch,
    };

    fn create_test_proposal() -> ProposalV2 {
        ProposalV2 {
            account_type: GovernanceAccountType::TokenOwnerRecordV2,
            governance: Pubkey::new_unique(),
            governing_token_mint: Pubkey::new_unique(),
            max_vote_weight: Some(10),
            state: ProposalState::Draft,
            token_owner_record: Pubkey::new_unique(),
            signatories_count: 10,
            signatories_signed_off_count: 5,
            description_link: "This is my description".to_string(),
            name: "This is my name".to_string(),

            start_voting_at: Some(0),
            draft_at: 10,
            signing_off_at: Some(10),

            voting_at: Some(10),
            voting_at_slot: Some(500),

            voting_completed_at: Some(10),
            executing_at: Some(10),
            closed_at: Some(10),

            vote_type: VoteType::SingleChoice,
            options: vec![ProposalOption {
                label: "yes".to_string(),
                vote_weight: 0,
                vote_result: OptionVoteResult::None,
                transactions_executed_count: 10,
                transactions_count: 10,
                transactions_next_index: 10,
            }],
            deny_vote_weight: Some(0),
            abstain_vote_weight: Some(0),
            veto_vote_weight: 0,

            execution_flags: InstructionExecutionFlags::Ordered,

            max_voting_time: Some(0),
            vote_threshold: Some(VoteThreshold::YesVotePercentage(100)),

            reserved: [0; 64],
            reserved1: 0,
        }
    }

    fn create_test_multi_option_proposal() -> ProposalV2 {
        let mut proposal = create_test_proposal();
        proposal.options = vec![
            ProposalOption {
                label: "option 1".to_string(),
                vote_weight: 0,
                vote_result: OptionVoteResult::None,
                transactions_executed_count: 10,
                transactions_count: 10,
                transactions_next_index: 10,
            },
            ProposalOption {
                label: "option 2".to_string(),
                vote_weight: 0,
                vote_result: OptionVoteResult::None,
                transactions_executed_count: 10,
                transactions_count: 10,
                transactions_next_index: 10,
            },
            ProposalOption {
                label: "option 3".to_string(),
                vote_weight: 0,
                vote_result: OptionVoteResult::None,
                transactions_executed_count: 10,
                transactions_count: 10,
                transactions_next_index: 10,
            },
        ];

        proposal
    }

    fn create_test_realm() -> RealmV2 {
        RealmV2 {
            account_type: GovernanceAccountType::RealmV2,
            community_mint: Pubkey::new_unique(),
            reserved: [0; 6],

            authority: Some(Pubkey::new_unique()),
            name: "test-realm".to_string(),
            config: RealmConfig {
                council_mint: Some(Pubkey::new_unique()),
                reserved: [0; 6],
                legacy1: 0,
                legacy2: 0,

                community_mint_max_voter_weight_source:
                    MintMaxVoterWeightSource::FULL_SUPPLY_FRACTION,
                min_community_weight_to_create_governance: 10,
            },
            legacy1: 0,
            reserved_v2: [0; 128],
        }
    }

    fn create_test_governance_config() -> GovernanceConfig {
        GovernanceConfig {
            community_vote_threshold: VoteThreshold::YesVotePercentage(60),
            min_community_weight_to_create_proposal: 5,
            min_transaction_hold_up_time: 10,
            voting_base_time: 5,
            community_vote_tipping: VoteTipping::Strict,
            council_vote_threshold: VoteThreshold::YesVotePercentage(60),
            council_veto_vote_threshold: VoteThreshold::YesVotePercentage(50),
            min_council_weight_to_create_proposal: 1,
            council_vote_tipping: VoteTipping::Strict,
            community_veto_vote_threshold: VoteThreshold::YesVotePercentage(40),
            voting_cool_off_time: 0,
            deposit_exempt_proposal_count: 0,
        }
    }

    #[test]
    fn test_max_size() {
        let mut proposal = create_test_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 1,
            max_winning_options: 1,
        };

        let size = proposal.try_to_vec().unwrap().len();

        assert_eq!(proposal.get_max_size(), Some(size));
    }

    #[test]
    fn test_multi_option_proposal_max_size() {
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let size = proposal.try_to_vec().unwrap().len();

        assert_eq!(proposal.get_max_size(), Some(size));
    }

    prop_compose! {
        fn vote_results()(governing_token_supply in 1..=u64::MAX)(
            governing_token_supply in Just(governing_token_supply),
            vote_count in 0..=governing_token_supply,
        ) -> (u64, u64) {
            (vote_count, governing_token_supply)
        }
    }

    fn editable_signatory_states() -> impl Strategy<Value = ProposalState> {
        prop_oneof![Just(ProposalState::Draft)]
    }

    proptest! {
        #[test]
        fn test_assert_can_edit_signatories(state in editable_signatory_states()) {

            let mut proposal = create_test_proposal();
            proposal.state = state;
            proposal.assert_can_edit_signatories().unwrap();

        }

    }

    fn none_editable_signatory_states() -> impl Strategy<Value = ProposalState> {
        prop_oneof![
            Just(ProposalState::Voting),
            Just(ProposalState::Succeeded),
            Just(ProposalState::Executing),
            Just(ProposalState::ExecutingWithErrors),
            Just(ProposalState::Completed),
            Just(ProposalState::Cancelled),
            Just(ProposalState::Defeated),
            Just(ProposalState::Vetoed),
            Just(ProposalState::SigningOff),
        ]
    }

    proptest! {
        #[test]
            fn test_assert_can_edit_signatories_with_invalid_state_error(state in none_editable_signatory_states()) {
                // Arrange
                let mut proposal = create_test_proposal();
                proposal.state = state;

                // Act
                let err = proposal.assert_can_edit_signatories().err().unwrap();

                // Assert
                assert_eq!(err, GovernanceError::InvalidStateCannotEditSignatories.into());
        }

    }

    fn sign_off_states() -> impl Strategy<Value = ProposalState> {
        prop_oneof![Just(ProposalState::SigningOff), Just(ProposalState::Draft),]
    }
    proptest! {
        #[test]
        fn test_assert_can_sign_off(state in sign_off_states()) {
            let mut proposal = create_test_proposal();
            proposal.state = state;
            proposal.assert_can_sign_off().unwrap();
        }
    }

    fn none_sign_off_states() -> impl Strategy<Value = ProposalState> {
        prop_oneof![
            Just(ProposalState::Voting),
            Just(ProposalState::Succeeded),
            Just(ProposalState::Executing),
            Just(ProposalState::ExecutingWithErrors),
            Just(ProposalState::Completed),
            Just(ProposalState::Cancelled),
            Just(ProposalState::Defeated),
            Just(ProposalState::Vetoed),
        ]
    }

    proptest! {
        #[test]
        fn test_assert_can_sign_off_with_state_error(state in none_sign_off_states()) {
                // Arrange
                let mut proposal = create_test_proposal();
                proposal.state = state;

                // Act
                let err = proposal.assert_can_sign_off().err().unwrap();

                // Assert
                assert_eq!(err, GovernanceError::InvalidStateCannotSignOff.into());
        }
    }

    fn cancellable_states() -> impl Strategy<Value = ProposalState> {
        prop_oneof![
            Just(ProposalState::Draft),
            Just(ProposalState::SigningOff),
            Just(ProposalState::Voting),
        ]
    }

    proptest! {
        #[test]
        fn test_assert_can_cancel(state in cancellable_states()) {

            // Arrange
            let mut proposal = create_test_proposal();
            let governance_config = create_test_governance_config();

            // Act
            proposal.state = state;

            // Assert
            proposal.assert_can_cancel(&governance_config,1).unwrap();

        }

    }

    fn none_cancellable_states() -> impl Strategy<Value = ProposalState> {
        prop_oneof![
            Just(ProposalState::Succeeded),
            Just(ProposalState::Executing),
            Just(ProposalState::ExecutingWithErrors),
            Just(ProposalState::Completed),
            Just(ProposalState::Cancelled),
            Just(ProposalState::Defeated),
            Just(ProposalState::Vetoed),
        ]
    }

    proptest! {
        #[test]
            fn test_assert_can_cancel_with_invalid_state_error(state in none_cancellable_states()) {
                // Arrange
                let mut proposal = create_test_proposal();
                proposal.state = state;

                let governance_config = create_test_governance_config();

                // Act
                let err = proposal.assert_can_cancel(&governance_config,1).err().unwrap();

                // Assert
                assert_eq!(err, GovernanceError::InvalidStateCannotCancelProposal.into());
        }

    }

    #[derive(Clone, Debug)]
    pub struct VoteCastTestCase {
        #[allow(dead_code)]
        name: &'static str,
        governing_token_supply: u64,
        yes_vote_threshold_percentage: u8,
        yes_votes_count: u64,
        no_votes_count: u64,
        expected_tipped_state: ProposalState,
        expected_finalized_state: ProposalState,
    }

    fn vote_casting_test_cases() -> impl Strategy<Value = VoteCastTestCase> {
        prop_oneof![
            //  threshold < 50%
            Just(VoteCastTestCase {
                name: "45:10 @40 -- Nays can still outvote Yeahs",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 45,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "49:50 @40 -- In best case scenario it can be 50:50 tie and hence Defeated",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 49,
                no_votes_count: 50,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "40:40 @40 -- Still can go either way",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 40,
                no_votes_count: 40,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "45:45 @40 -- Still can go either way",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 45,
                no_votes_count: 45,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "50:10 @40 -- Nay sayers can still tie up",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 50,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "50:50 @40 -- It's a tie and hence Defeated",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 50,
                no_votes_count: 50,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "45:51 @ 40 -- Nays won",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 45,
                no_votes_count: 51,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "40:55 @ 40 -- Nays won",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 40,
                yes_votes_count: 40,
                no_votes_count: 55,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            // threshold == 50%
            Just(VoteCastTestCase {
                name: "50:10 @50 -- +1 tie breaker required to tip",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 50,
                yes_votes_count: 50,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "10:50 @50 -- +1 tie breaker vote not possible any longer",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 50,
                yes_votes_count: 10,
                no_votes_count: 50,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "50:50 @50 -- +1 tie breaker vote not possible any longer",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 50,
                yes_votes_count: 50,
                no_votes_count: 50,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "51:10 @ 50 -- Nay sayers can't outvote any longer",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 50,
                yes_votes_count: 51,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Succeeded,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "10:51 @ 50 -- Nays won",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 50,
                yes_votes_count: 10,
                no_votes_count: 51,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            // threshold > 50%
            Just(VoteCastTestCase {
                name: "10:10 @ 60 -- Can still go either way",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 60,
                yes_votes_count: 10,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "55:10 @ 60 -- Can still go either way",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 60,
                yes_votes_count: 55,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "60:10 @ 60 -- Yeah reached the required threshold",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 60,
                yes_votes_count: 60,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Succeeded,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "61:10 @ 60 -- Yeah won",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 60,
                yes_votes_count: 61,
                no_votes_count: 10,
                expected_tipped_state: ProposalState::Succeeded,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "10:40 @ 60 -- Yeah can still outvote Nay",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 60,
                yes_votes_count: 10,
                no_votes_count: 40,
                expected_tipped_state: ProposalState::Voting,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "60:40 @ 60 -- Yeah won",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 60,
                yes_votes_count: 60,
                no_votes_count: 40,
                expected_tipped_state: ProposalState::Succeeded,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "10:41 @ 60 -- Aye can't outvote Nay any longer",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 60,
                yes_votes_count: 10,
                no_votes_count: 41,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
            Just(VoteCastTestCase {
                name: "100:0",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 100,
                yes_votes_count: 100,
                no_votes_count: 0,
                expected_tipped_state: ProposalState::Succeeded,
                expected_finalized_state: ProposalState::Succeeded,
            }),
            Just(VoteCastTestCase {
                name: "0:100",
                governing_token_supply: 100,
                yes_vote_threshold_percentage: 100,
                yes_votes_count: 0,
                no_votes_count: 100,
                expected_tipped_state: ProposalState::Defeated,
                expected_finalized_state: ProposalState::Defeated,
            }),
        ]
    }

    proptest! {
        #[test]
        fn test_try_tip_vote(test_case in vote_casting_test_cases()) {
            // Arrange
            let mut proposal = create_test_proposal();

           proposal.options[0].vote_weight = test_case.yes_votes_count;
           proposal.deny_vote_weight = Some(test_case.no_votes_count);

            proposal.state = ProposalState::Voting;


            let current_timestamp = 15_i64;

            let realm = create_test_realm();
            let governing_token_mint = proposal.governing_token_mint;
            let vote_kind = VoteKind::Electorate;
            let vote_tipping = VoteTipping::Strict;

            let max_voter_weight = proposal.get_max_voter_weight_from_mint_supply(&realm,&governing_token_mint, test_case.governing_token_supply,&vote_kind).unwrap();
            let vote_threshold = VoteThreshold::YesVotePercentage(test_case.yes_vote_threshold_percentage);



            // Act
            proposal.try_tip_vote(max_voter_weight, &vote_tipping,current_timestamp,&vote_threshold,&vote_kind).unwrap();

            // Assert
            assert_eq!(proposal.state,test_case.expected_tipped_state,"CASE: {:?}",test_case);

            if test_case.expected_tipped_state != ProposalState::Voting {
                assert_eq!(Some(current_timestamp),proposal.voting_completed_at);

            }

            match proposal.options[0].vote_result {
                OptionVoteResult::Succeeded => {
                    assert_eq!(ProposalState::Succeeded,test_case.expected_tipped_state)
                },
                OptionVoteResult::Defeated => {
                    assert_eq!(ProposalState::Defeated,test_case.expected_tipped_state)
                },
                OptionVoteResult::None =>  {
                    assert_eq!(ProposalState::Voting,test_case.expected_tipped_state)
                },
            };

        }

        #[test]
        fn test_finalize_vote(test_case in vote_casting_test_cases()) {
            // Arrange
            let mut proposal = create_test_proposal();

            proposal.options[0].vote_weight = test_case.yes_votes_count;
            proposal.deny_vote_weight = Some(test_case.no_votes_count);

            proposal.state = ProposalState::Voting;

            let governance_config = create_test_governance_config();

            let current_timestamp = 16_i64;

            let realm = create_test_realm();
            let governing_token_mint = proposal.governing_token_mint;
            let vote_kind = VoteKind::Electorate;

            let max_voter_weight = proposal.get_max_voter_weight_from_mint_supply(&realm,&governing_token_mint,test_case.governing_token_supply,&vote_kind).unwrap();
            let vote_threshold = VoteThreshold::YesVotePercentage(test_case.yes_vote_threshold_percentage);

            // Act
            proposal.finalize_vote(max_voter_weight, &governance_config,current_timestamp,&vote_threshold).unwrap();

            // Assert
            assert_eq!(proposal.state,test_case.expected_finalized_state,"CASE: {:?}",test_case);
            assert_eq!(
                Some(proposal.voting_max_time_end(&governance_config)),
                proposal.voting_completed_at
            );

            match proposal.options[0].vote_result {
                OptionVoteResult::Succeeded => {
                    assert_eq!(ProposalState::Succeeded,test_case.expected_finalized_state)
                },
                OptionVoteResult::Defeated => {
                    assert_eq!(ProposalState::Defeated,test_case.expected_finalized_state)
                },
                OptionVoteResult::None =>  {
                    panic!("Option result must be resolved for finalized vote")
                },
            };

        }
    }

    prop_compose! {
        fn full_vote_results()(governing_token_supply in 1..=u64::MAX, yes_vote_threshold in 1..100)(
            governing_token_supply in Just(governing_token_supply),
            yes_vote_threshold in Just(yes_vote_threshold),

            yes_votes_count in 0..=governing_token_supply,
            no_votes_count in 0..=governing_token_supply,

        ) -> (u64, u64, u64, u8) {
            (yes_votes_count, no_votes_count, governing_token_supply, yes_vote_threshold as u8)
        }
    }

    proptest! {
        #[test]
        fn test_try_tip_vote_with_full_vote_results(
            (yes_votes_count, no_votes_count, governing_token_supply, yes_vote_threshold_percentage) in full_vote_results(),

        ) {
            // Arrange

            let mut proposal = create_test_proposal();

            proposal.options[0].vote_weight = yes_votes_count;
            proposal.deny_vote_weight = Some(no_votes_count.min(governing_token_supply-yes_votes_count));


            proposal.state = ProposalState::Voting;



            let  yes_vote_threshold_percentage = VoteThreshold::YesVotePercentage(yes_vote_threshold_percentage);

            let current_timestamp = 15_i64;

            let realm = create_test_realm();
            let governing_token_mint = proposal.governing_token_mint;
            let vote_kind = VoteKind::Electorate;
            let vote_tipping = VoteTipping::Strict;

            let max_voter_weight = proposal.get_max_voter_weight_from_mint_supply(&realm,&governing_token_mint,governing_token_supply,&vote_kind).unwrap();

            // Act
            proposal.try_tip_vote(max_voter_weight, &vote_tipping, current_timestamp,&yes_vote_threshold_percentage,&vote_kind).unwrap();

            // Assert
            let yes_vote_threshold_count = get_min_vote_threshold_weight(&yes_vote_threshold_percentage,governing_token_supply).unwrap();

            let no_vote_weight = proposal.deny_vote_weight.unwrap();

            if yes_votes_count >= yes_vote_threshold_count && yes_votes_count > (governing_token_supply - yes_votes_count)
            {
                assert_eq!(proposal.state,ProposalState::Succeeded);
            } else if no_vote_weight > (governing_token_supply - yes_vote_threshold_count)
                || no_vote_weight >= (governing_token_supply - no_vote_weight ) {
                assert_eq!(proposal.state,ProposalState::Defeated);
            } else {
                assert_eq!(proposal.state,ProposalState::Voting);
            }
        }
    }

    proptest! {
        #[test]
        fn test_finalize_vote_with_full_vote_results(
            (yes_votes_count, no_votes_count, governing_token_supply, yes_vote_threshold_percentage) in full_vote_results(),

        ) {
            // Arrange
            let mut proposal = create_test_proposal();

            proposal.options[0].vote_weight = yes_votes_count;
            proposal.deny_vote_weight = Some(no_votes_count.min(governing_token_supply-yes_votes_count));

            proposal.state = ProposalState::Voting;


            let governance_config = create_test_governance_config();
            let  yes_vote_threshold_percentage = VoteThreshold::YesVotePercentage(yes_vote_threshold_percentage);


            let current_timestamp = 16_i64;

            let realm = create_test_realm();
            let governing_token_mint = proposal.governing_token_mint;
            let vote_kind = VoteKind::Electorate;

            let max_voter_weight = proposal.get_max_voter_weight_from_mint_supply(&realm,&governing_token_mint,governing_token_supply,&vote_kind).unwrap();

            // Act
            proposal.finalize_vote(max_voter_weight, &governance_config,current_timestamp, &yes_vote_threshold_percentage).unwrap();

            // Assert
            let no_vote_weight = proposal.deny_vote_weight.unwrap();

            let yes_vote_threshold_count = get_min_vote_threshold_weight(&yes_vote_threshold_percentage,governing_token_supply).unwrap();

            if yes_votes_count >= yes_vote_threshold_count &&  yes_votes_count > no_vote_weight
            {
                assert_eq!(proposal.state,ProposalState::Succeeded);
            } else {
                assert_eq!(proposal.state,ProposalState::Defeated);
            }
        }
    }

    #[test]
    fn test_try_tip_vote_with_reduced_community_mint_max_vote_weight() {
        // Arrange
        let mut proposal = create_test_proposal();

        proposal.options[0].vote_weight = 60;
        proposal.deny_vote_weight = Some(10);

        proposal.state = ProposalState::Voting;

        let current_timestamp = 15_i64;

        let community_token_supply = 200;

        let mut realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;
        let vote_tipping = VoteTipping::Strict;

        // reduce max vote weight to 100
        realm.config.community_mint_max_voter_weight_source =
            MintMaxVoterWeightSource::SupplyFraction(
                MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE / 2,
            );

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(
                &realm,
                &governing_token_mint,
                community_token_supply,
                &vote_kind,
            )
            .unwrap();

        let vote_threshold = &VoteThreshold::YesVotePercentage(60);
        let vote_kind = VoteKind::Electorate;

        // Act
        proposal
            .try_tip_vote(
                max_voter_weight,
                &vote_tipping,
                current_timestamp,
                vote_threshold,
                &vote_kind,
            )
            .unwrap();

        // Assert
        assert_eq!(proposal.state, ProposalState::Succeeded);
        assert_eq!(proposal.max_vote_weight, Some(100));
    }

    #[test]
    fn test_try_tip_vote_with_reduced_absolute_community_mint_max_vote_weight() {
        // Arrange
        let mut proposal = create_test_proposal();

        proposal.options[0].vote_weight = 60;
        proposal.deny_vote_weight = Some(10);

        proposal.state = ProposalState::Voting;

        let current_timestamp = 15_i64;

        let community_token_supply = 200;

        let mut realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;
        let vote_tipping = VoteTipping::Strict;

        // set max vote weight to 100
        realm.config.community_mint_max_voter_weight_source =
            MintMaxVoterWeightSource::Absolute(community_token_supply / 2);

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(
                &realm,
                &governing_token_mint,
                community_token_supply,
                &vote_kind,
            )
            .unwrap();

        let vote_threshold = &VoteThreshold::YesVotePercentage(60);
        let vote_kind = VoteKind::Electorate;

        // Act
        proposal
            .try_tip_vote(
                max_voter_weight,
                &vote_tipping,
                current_timestamp,
                vote_threshold,
                &vote_kind,
            )
            .unwrap();

        // Assert
        assert_eq!(proposal.state, ProposalState::Succeeded);
        assert_eq!(proposal.max_vote_weight, Some(100));
    }

    #[test]
    fn test_try_tip_vote_with_reduced_community_mint_max_vote_weight_and_vote_overflow() {
        // Arrange
        let mut proposal = create_test_proposal();

        // no vote weight
        proposal.deny_vote_weight = Some(10);

        proposal.state = ProposalState::Voting;

        let current_timestamp = 15_i64;

        let community_token_supply = 200;

        let mut realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;
        let vote_tipping = VoteTipping::Strict;

        // reduce max vote weight to 100
        realm.config.community_mint_max_voter_weight_source =
            MintMaxVoterWeightSource::SupplyFraction(
                MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE / 2,
            );

        // vote above reduced supply
        // Yes vote weight
        proposal.options[0].vote_weight = 120;

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(
                &realm,
                &governing_token_mint,
                community_token_supply,
                &vote_kind,
            )
            .unwrap();

        let vote_threshold = VoteThreshold::YesVotePercentage(60);

        // Act
        proposal
            .try_tip_vote(
                max_voter_weight,
                &vote_tipping,
                current_timestamp,
                &vote_threshold,
                &vote_kind,
            )
            .unwrap();

        // Assert
        assert_eq!(proposal.state, ProposalState::Succeeded);
        assert_eq!(proposal.max_vote_weight, Some(130));
    }

    #[test]
    fn test_try_tip_vote_with_reduced_absolute_mint_max_vote_weight_and_vote_overflow() {
        // Arrange
        let mut proposal = create_test_proposal();

        // no vote weight
        proposal.deny_vote_weight = Some(10);

        proposal.state = ProposalState::Voting;

        let current_timestamp = 15_i64;

        let community_token_supply = 200;

        let mut realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;
        let vote_tipping = VoteTipping::Strict;

        // reduce max vote weight to 100
        realm.config.community_mint_max_voter_weight_source =
            MintMaxVoterWeightSource::Absolute(community_token_supply / 2);

        // vote above reduced supply
        // Yes vote weight
        proposal.options[0].vote_weight = 120;

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(
                &realm,
                &governing_token_mint,
                community_token_supply,
                &vote_kind,
            )
            .unwrap();

        let vote_threshold = VoteThreshold::YesVotePercentage(60);

        // Act
        proposal
            .try_tip_vote(
                max_voter_weight,
                &vote_tipping,
                current_timestamp,
                &vote_threshold,
                &vote_kind,
            )
            .unwrap();

        // Assert
        assert_eq!(proposal.state, ProposalState::Succeeded);
        assert_eq!(proposal.max_vote_weight, Some(130)); // Deny Vote 10 +
                                                         // Approve Vote 120
    }

    #[test]
    fn test_try_tip_vote_for_council_vote_with_reduced_community_mint_max_vote_weight() {
        // Arrange
        let mut proposal = create_test_proposal();

        proposal.options[0].vote_weight = 60;
        proposal.deny_vote_weight = Some(10);

        proposal.state = ProposalState::Voting;

        let current_timestamp = 15_i64;

        let community_token_supply = 200;

        let mut realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;
        let vote_tipping = VoteTipping::Strict;

        realm.config.community_mint_max_voter_weight_source =
            MintMaxVoterWeightSource::SupplyFraction(
                MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE / 2,
            );
        realm.config.council_mint = Some(proposal.governing_token_mint);

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(
                &realm,
                &governing_token_mint,
                community_token_supply,
                &vote_kind,
            )
            .unwrap();

        let vote_threshold = VoteThreshold::YesVotePercentage(60);

        // Act
        proposal
            .try_tip_vote(
                max_voter_weight,
                &vote_tipping,
                current_timestamp,
                &vote_threshold,
                &vote_kind,
            )
            .unwrap();

        // Assert
        assert_eq!(proposal.state, ProposalState::Voting);
    }

    #[test]
    fn test_finalize_vote_with_reduced_community_mint_max_vote_weight() {
        // Arrange
        let mut proposal = create_test_proposal();

        proposal.options[0].vote_weight = 60;
        proposal.deny_vote_weight = Some(10);

        proposal.state = ProposalState::Voting;

        let governance_config = create_test_governance_config();

        let current_timestamp = 16_i64;
        let community_token_supply = 200;

        let mut realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;

        // reduce max vote weight to 100
        realm.config.community_mint_max_voter_weight_source =
            MintMaxVoterWeightSource::SupplyFraction(
                MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE / 2,
            );

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(
                &realm,
                &governing_token_mint,
                community_token_supply,
                &vote_kind,
            )
            .unwrap();

        let vote_threshold = VoteThreshold::YesVotePercentage(60);

        // Act
        proposal
            .finalize_vote(
                max_voter_weight,
                &governance_config,
                current_timestamp,
                &vote_threshold,
            )
            .unwrap();

        // Assert
        assert_eq!(proposal.state, ProposalState::Succeeded);
        assert_eq!(proposal.max_vote_weight, Some(100));
    }

    #[test]
    fn test_finalize_vote_with_reduced_community_mint_max_vote_weight_and_vote_overflow() {
        // Arrange
        let mut proposal = create_test_proposal();

        proposal.options[0].vote_weight = 60;
        proposal.deny_vote_weight = Some(10);

        proposal.state = ProposalState::Voting;

        let governance_config = create_test_governance_config();

        let current_timestamp = 16_i64;
        let community_token_supply = 200;

        let mut realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;

        // reduce max vote weight to 100
        realm.config.community_mint_max_voter_weight_source =
            MintMaxVoterWeightSource::SupplyFraction(
                MintMaxVoterWeightSource::SUPPLY_FRACTION_BASE / 2,
            );

        // vote above reduced supply
        proposal.options[0].vote_weight = 120;

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(
                &realm,
                &governing_token_mint,
                community_token_supply,
                &vote_kind,
            )
            .unwrap();

        let vote_threshold = VoteThreshold::YesVotePercentage(60);

        // Act
        proposal
            .finalize_vote(
                max_voter_weight,
                &governance_config,
                current_timestamp,
                &vote_threshold,
            )
            .unwrap();

        // Assert
        assert_eq!(proposal.state, ProposalState::Succeeded);
        assert_eq!(proposal.max_vote_weight, Some(130));
    }

    #[test]
    pub fn test_finalize_vote_with_expired_voting_time_error() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;
        let governance_config = create_test_governance_config();

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64;

        let realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(&realm, &governing_token_mint, 100, &vote_kind)
            .unwrap();

        let vote_threshold = &governance_config.community_vote_threshold;

        // Act
        let err = proposal
            .finalize_vote(
                max_voter_weight,
                &governance_config,
                current_timestamp,
                vote_threshold,
            )
            .err()
            .unwrap();

        // Assert
        assert_eq!(err, GovernanceError::CannotFinalizeVotingInProgress.into());
    }

    #[test]
    pub fn test_finalize_vote_after_voting_time() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;
        let governance_config = create_test_governance_config();

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64 + 1;

        let realm = create_test_realm();
        let governing_token_mint = proposal.governing_token_mint;
        let vote_kind = VoteKind::Electorate;

        let max_voter_weight = proposal
            .get_max_voter_weight_from_mint_supply(&realm, &governing_token_mint, 100, &vote_kind)
            .unwrap();

        let vote_threshold = &governance_config.community_vote_threshold;

        // Act
        let result = proposal.finalize_vote(
            max_voter_weight,
            &governance_config,
            current_timestamp,
            vote_threshold,
        );

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_can_vote_with_expired_voting_time_error() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;
        let governance_config = create_test_governance_config();

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64 + 1;

        let vote = Vote::Approve(vec![]);

        // Act
        let err = proposal
            .assert_can_cast_vote(&governance_config, &vote, current_timestamp)
            .err()
            .unwrap();

        // Assert
        assert_eq!(err, GovernanceError::ProposalVotingTimeExpired.into());
    }

    #[test]
    pub fn test_assert_can_vote_within_voting_time() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;
        let governance_config = create_test_governance_config();

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64;

        let vote = Vote::Approve(vec![]);

        // Act
        let result = proposal.assert_can_cast_vote(&governance_config, &vote, current_timestamp);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_can_vote_approve_before_voting_cool_off_time() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;

        let mut governance_config = create_test_governance_config();
        governance_config.voting_cool_off_time = 2;

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64 - 1;

        let vote = Vote::Approve(vec![]);

        // Act
        let result = proposal.assert_can_cast_vote(&governance_config, &vote, current_timestamp);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_cannot_vote_approve_within_voting_cool_off_time() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;

        let mut governance_config = create_test_governance_config();
        governance_config.voting_cool_off_time = 2;

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64 + 1;

        let vote = Vote::Approve(vec![]);

        // Act
        let err = proposal
            .assert_can_cast_vote(&governance_config, &vote, current_timestamp)
            .err()
            .unwrap();

        // Assert
        assert_eq!(err, GovernanceError::VoteNotAllowedInCoolOffTime.into());
    }

    #[test]
    pub fn test_assert_can_vote_veto_within_voting_cool_off_time() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;

        let mut governance_config = create_test_governance_config();
        governance_config.voting_cool_off_time = 2;

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64 + 1;

        let vote = Vote::Veto;

        // Act
        let result = proposal.assert_can_cast_vote(&governance_config, &vote, current_timestamp);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_can_vote_deny_within_voting_cool_off_time() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.state = ProposalState::Voting;

        let mut governance_config = create_test_governance_config();
        governance_config.voting_cool_off_time = 1;

        let current_timestamp =
            proposal.voting_at.unwrap() + governance_config.voting_base_time as i64 + 1;

        let vote = Vote::Deny;

        // Act
        let result = proposal.assert_can_cast_vote(&governance_config, &vote, current_timestamp);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_valid_vote_with_deny_vote_for_survey_only_proposal_error() {
        // Arrange
        let mut proposal = create_test_proposal();
        proposal.deny_vote_weight = None;

        // Survey only proposal can't be denied
        let vote = Vote::Deny;

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(result, Err(GovernanceError::DenyVoteIsNotAllowed.into()));
    }

    #[test]
    pub fn test_assert_valid_vote_with_too_many_options_error() {
        // Arrange
        let proposal = create_test_proposal();

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
        ];

        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert!(proposal.options.len() != choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::InvalidNumberOfVoteChoices.into())
        );
    }

    #[test]
    pub fn test_assert_valid_vote_with_no_choice_for_single_choice_error() {
        // Arrange
        let proposal = create_test_proposal();

        let choices = vec![VoteChoice {
            rank: 0,
            weight_percentage: 0,
        }];

        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::SingleChoiceOnlyIsAllowed.into())
        );
    }

    #[test]
    pub fn test_assert_valid_vote_with_to_many_choices_for_single_choice_error() {
        // Arrange
        let proposal = create_test_multi_option_proposal();
        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 0,
            },
        ];

        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::SingleChoiceOnlyIsAllowed.into())
        );
    }

    #[test]
    pub fn test_assert_valid_multi_choice_full_weight_vote() {
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 4,
            max_winning_options: 4,
        };
        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
        ];

        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_valid_vote_with_no_choices_for_multi_choice_error() {
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 0,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 0,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 0,
            },
        ];

        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::AtLeastSingleChoiceIsRequired.into())
        );
    }

    #[test]
    pub fn test_assert_valid_vote_with_choice_weight_not_100_percent_error() {
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 50,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 50,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 0,
            },
        ];

        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::ChoiceWeightMustBe100Percent.into())
        );
    }

    #[test]
    pub fn test_assert_valid_proposal_options_with_invalid_choice_number_for_multi_choice_vote_error(
    ) {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec!["option 1".to_string(), "option 2".to_string()];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::InvalidMultiChoiceProposalParameters.into())
        );
    }

    #[test]
    pub fn test_assert_valid_proposal_options_with_no_options_for_multi_choice_vote_error() {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec![];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Err(GovernanceError::InvalidProposalOptions.into()));
    }

    #[test]
    pub fn test_assert_valid_proposal_options_with_no_options_for_single_choice_vote_error() {
        // Arrange
        let vote_type = VoteType::SingleChoice;

        let options = vec![];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Err(GovernanceError::InvalidProposalOptions.into()));
    }

    #[test]
    pub fn test_assert_valid_proposal_options_for_multi_choice_vote() {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec![
            "option 1".to_string(),
            "option 2".to_string(),
            "option 3".to_string(),
        ];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_valid_proposal_options_for_multi_choice_vote_with_empty_option_error() {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::FullWeight,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec![
            "".to_string(),
            "option 2".to_string(),
            "option 3".to_string(),
        ];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Err(GovernanceError::InvalidProposalOptions.into()));
    }

    #[test]
    pub fn test_assert_valid_vote_for_multi_weighted_choice() {
        // Multi weighted choice may be weighted but sum of choices has to be 100%
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 42,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 42,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 16,
            },
        ];
        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_valid_full_vote_for_multi_weighted_choice() {
        // Multi weighted choice may be weighted to 100% and 0% rest
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 0,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 0,
            },
        ];
        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_valid_vote_with_total_vote_weight_above_100_percent_for_multi_weighted_choice_error(
    ) {
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 2,
            max_winning_options: 2,
        };

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 34,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 34,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 34,
            },
        ];
        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::TotalVoteWeightMustBe100Percent.into())
        );
    }

    #[test]
    pub fn test_assert_valid_vote_with_over_percentage_for_multi_weighted_choice_error() {
        // Multi weighted choice does not permit vote with sum weight over 100%
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 34,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 34,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 34,
            },
        ];
        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::TotalVoteWeightMustBe100Percent.into())
        );
    }

    #[test]
    pub fn test_assert_valid_vote_with_overflow_weight_for_multi_weighted_choice_error() {
        // Multi weighted choice does not permit vote with sum weight over 100%
        // Arrange
        let mut proposal = create_test_multi_option_proposal();
        proposal.vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let choices = vec![
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
            VoteChoice {
                rank: 0,
                weight_percentage: 100,
            },
        ];
        let vote = Vote::Approve(choices.clone());

        // Ensure
        assert_eq!(proposal.options.len(), choices.len());

        // Act
        let result = proposal.assert_valid_vote(&vote);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::TotalVoteWeightMustBe100Percent.into())
        );
    }

    #[test]
    pub fn test_assert_valid_proposal_options_with_invalid_choice_number_for_multi_weighted_choice_vote_error(
    ) {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec!["option 1".to_string(), "option 2".to_string()];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(
            result,
            Err(GovernanceError::InvalidMultiChoiceProposalParameters.into())
        );
    }

    #[test]
    pub fn test_assert_valid_proposal_options_with_no_options_for_multi_weighted_choice_vote_error()
    {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec![];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Err(GovernanceError::InvalidProposalOptions.into()));
    }

    #[test]
    pub fn test_assert_valid_proposal_options_for_multi_weighted_choice_vote() {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec![
            "option 1".to_string(),
            "option 2".to_string(),
            "option 3".to_string(),
        ];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Ok(()));
    }

    #[test]
    pub fn test_assert_valid_proposal_options_for_multi_weighted_choice_vote_with_empty_option_error(
    ) {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec![
            "".to_string(),
            "option 2".to_string(),
            "option 3".to_string(),
        ];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Err(GovernanceError::InvalidProposalOptions.into()));
    }

    #[test]
    pub fn test_assert_more_than_ten_proposal_options_for_multi_weighted_choice_error() {
        // Arrange
        let vote_type = VoteType::MultiChoice {
            choice_type: MultiChoiceType::Weighted,
            min_voter_options: 1,
            max_voter_options: 3,
            max_winning_options: 3,
        };

        let options = vec![
            "option 1".to_string(),
            "option 2".to_string(),
            "option 3".to_string(),
            "option 4".to_string(),
            "option 5".to_string(),
            "option 6".to_string(),
            "option 7".to_string(),
            "option 8".to_string(),
            "option 9".to_string(),
            "option 10".to_string(),
            "option 11".to_string(),
        ];

        // Act
        let result = assert_valid_proposal_options(&options, &vote_type);

        // Assert
        assert_eq!(result, Err(GovernanceError::InvalidProposalOptions.into()));
    }

    #[test]
    fn test_proposal_v1_to_v2_serialisation_roundtrip() {
        // Arrange

        let proposal_v1_source = ProposalV1 {
            account_type: GovernanceAccountType::ProposalV1,
            governance: Pubkey::new_unique(),
            governing_token_mint: Pubkey::new_unique(),
            state: ProposalState::Executing,
            token_owner_record: Pubkey::new_unique(),
            signatories_count: 5,
            signatories_signed_off_count: 4,
            yes_votes_count: 100,
            no_votes_count: 80,
            instructions_executed_count: 7,
            instructions_count: 8,
            instructions_next_index: 9,
            draft_at: 200,
            signing_off_at: Some(201),
            voting_at: Some(202),
            voting_at_slot: Some(203),
            voting_completed_at: Some(204),
            executing_at: Some(205),
            closed_at: Some(206),
            execution_flags: InstructionExecutionFlags::None,
            max_vote_weight: Some(250),
            vote_threshold: Some(VoteThreshold::YesVotePercentage(65)),
            name: "proposal".to_string(),
            description_link: "proposal-description".to_string(),
        };

        let mut account_data = vec![];
        proposal_v1_source.serialize(&mut account_data).unwrap();

        let program_id = Pubkey::new_unique();

        let info_key = Pubkey::new_unique();
        let mut lamports = 10u64;

        let account_info = AccountInfo::new(
            &info_key,
            false,
            false,
            &mut lamports,
            &mut account_data[..],
            &program_id,
            false,
            Epoch::default(),
        );

        // Act

        let proposal_v2 = get_proposal_data(&program_id, &account_info).unwrap();

        proposal_v2
            .serialize(&mut account_info.data.borrow_mut()[..])
            .unwrap();

        // Assert
        let proposal_v1_target =
            get_account_data::<ProposalV1>(&program_id, &account_info).unwrap();

        assert_eq!(proposal_v1_source, proposal_v1_target)
    }
}