solana-stake-program 5.0.0

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

use {
    solana_account::Account as SolanaAccount,
    solana_clock::Clock,
    solana_instruction::Instruction,
    solana_keypair::Keypair,
    solana_program_entrypoint::ProgramResult,
    solana_program_error::ProgramError,
    solana_program_test::*,
    solana_pubkey::Pubkey,
    solana_rent::Rent,
    solana_sdk_ids::system_program,
    solana_signer::Signer,
    solana_stake_interface::{
        error::StakeError,
        instruction::{self as ixn, LockupArgs},
        program::id,
        stake_history::StakeHistory,
        state::{Authorized, Delegation, Lockup, Meta, Stake, StakeAuthorize, StakeStateV2},
    },
    solana_system_interface::instruction as system_instruction,
    solana_transaction::{Signers, Transaction, TransactionError},
    solana_vote_interface::{
        instruction as vote_instruction,
        state::{VoteInit, VoteStateV4},
    },
    test_case::{test_case, test_matrix},
};

pub const USER_STARTING_LAMPORTS: u64 = 10_000_000_000_000; // 10k sol
pub const NO_SIGNERS: &[Keypair] = &[];

pub fn program_test() -> ProgramTest {
    program_test_without_features(&[])
}

pub fn program_test_without_features(feature_ids: &[Pubkey]) -> ProgramTest {
    let mut program_test = ProgramTest::default();
    program_test.prefer_bpf(true);

    for feature_id in feature_ids {
        program_test.deactivate_feature(*feature_id);
    }

    program_test.add_upgradeable_program_to_genesis("solana_stake_program", &id());

    program_test
}

#[derive(Debug, PartialEq)]
pub struct Accounts {
    pub validator: Keypair,
    pub voter: Keypair,
    pub withdrawer: Keypair,
    pub vote_account: Keypair,
}

impl Accounts {
    pub async fn initialize(&self, context: &mut ProgramTestContext) {
        let slot = context.genesis_config().epoch_schedule.first_normal_slot + 1;
        context.warp_to_slot(slot).unwrap();

        create_vote(
            context,
            &self.validator,
            &self.voter.pubkey(),
            &self.withdrawer.pubkey(),
            &self.vote_account,
        )
        .await;
    }
}

impl Default for Accounts {
    fn default() -> Self {
        let vote_account = Keypair::new();

        Self {
            validator: Keypair::new(),
            voter: Keypair::new(),
            withdrawer: Keypair::new(),
            vote_account,
        }
    }
}

pub async fn create_vote(
    context: &mut ProgramTestContext,
    validator: &Keypair,
    voter: &Pubkey,
    withdrawer: &Pubkey,
    vote_account: &Keypair,
) {
    let rent = context.banks_client.get_rent().await.unwrap();
    let rent_voter = rent.minimum_balance(VoteStateV4::size_of());

    let mut instructions = vec![system_instruction::create_account(
        &context.payer.pubkey(),
        &validator.pubkey(),
        rent.minimum_balance(0),
        0,
        &system_program::id(),
    )];
    instructions.append(&mut vote_instruction::create_account_with_config(
        &context.payer.pubkey(),
        &vote_account.pubkey(),
        &VoteInit {
            node_pubkey: validator.pubkey(),
            authorized_voter: *voter,
            authorized_withdrawer: *withdrawer,
            ..VoteInit::default()
        },
        rent_voter,
        vote_instruction::CreateVoteAccountConfig {
            space: VoteStateV4::size_of() as u64,
            ..Default::default()
        },
    ));

    let transaction = Transaction::new_signed_with_payer(
        &instructions,
        Some(&context.payer.pubkey()),
        &[validator, vote_account, &context.payer],
        context.last_blockhash,
    );

    // ignore errors for idempotency
    let _ = context.banks_client.process_transaction(transaction).await;
}

pub async fn transfer(context: &mut ProgramTestContext, recipient: &Pubkey, amount: u64) {
    let transaction = Transaction::new_signed_with_payer(
        &[system_instruction::transfer(
            &context.payer.pubkey(),
            recipient,
            amount,
        )],
        Some(&context.payer.pubkey()),
        &[&context.payer],
        context.last_blockhash,
    );
    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();
}

pub async fn advance_epoch(context: &mut ProgramTestContext) {
    refresh_blockhash(context).await;

    let root_slot = context.banks_client.get_root_slot().await.unwrap();
    let slots_per_epoch = context.genesis_config().epoch_schedule.slots_per_epoch;
    context.warp_to_slot(root_slot + slots_per_epoch).unwrap();
}

pub async fn refresh_blockhash(context: &mut ProgramTestContext) {
    context.last_blockhash = context
        .banks_client
        .get_new_latest_blockhash(&context.last_blockhash)
        .await
        .unwrap();
}

pub async fn get_account(banks_client: &mut BanksClient, pubkey: &Pubkey) -> SolanaAccount {
    banks_client
        .get_account(*pubkey)
        .await
        .expect("client error")
        .expect("account not found")
}

pub async fn get_stake_account(
    banks_client: &mut BanksClient,
    pubkey: &Pubkey,
) -> (Meta, Option<Stake>, u64) {
    let stake_account = get_account(banks_client, pubkey).await;
    let lamports = stake_account.lamports;
    match bincode::deserialize::<StakeStateV2>(&stake_account.data).unwrap() {
        StakeStateV2::Initialized(meta) => (meta, None, lamports),
        StakeStateV2::Stake(meta, stake, _) => (meta, Some(stake), lamports),
        StakeStateV2::Uninitialized => panic!("panic: uninitialized"),
        _ => unimplemented!(),
    }
}

pub async fn get_stake_account_rent(banks_client: &mut BanksClient) -> u64 {
    let rent = banks_client.get_rent().await.unwrap();
    rent.minimum_balance(std::mem::size_of::<StakeStateV2>())
}

pub async fn get_effective_stake(banks_client: &mut BanksClient, pubkey: &Pubkey) -> u64 {
    let clock = banks_client.get_sysvar::<Clock>().await.unwrap();
    let stake_history = banks_client.get_sysvar::<StakeHistory>().await.unwrap();
    let stake_account = get_account(banks_client, pubkey).await;
    match bincode::deserialize::<StakeStateV2>(&stake_account.data).unwrap() {
        StakeStateV2::Stake(_, stake, _) => {
            stake
                .delegation
                .stake_activating_and_deactivating(clock.epoch, &stake_history, Some(0))
                .effective
        }
        _ => 0,
    }
}

async fn get_minimum_delegation(context: &mut ProgramTestContext) -> u64 {
    let transaction = Transaction::new_signed_with_payer(
        &[ixn::get_minimum_delegation()],
        Some(&context.payer.pubkey()),
        &[&context.payer],
        context.last_blockhash,
    );
    let mut data = context
        .banks_client
        .simulate_transaction(transaction)
        .await
        .unwrap()
        .simulation_details
        .unwrap()
        .return_data
        .unwrap()
        .data;
    data.resize(8, 0);

    data.try_into().map(u64::from_le_bytes).unwrap()
}

pub async fn create_independent_stake_account(
    context: &mut ProgramTestContext,
    authorized: &Authorized,
    stake_amount: u64,
) -> Pubkey {
    create_independent_stake_account_with_lockup(
        context,
        authorized,
        &Lockup::default(),
        stake_amount,
    )
    .await
}

pub async fn create_independent_stake_account_with_lockup(
    context: &mut ProgramTestContext,
    authorized: &Authorized,
    lockup: &Lockup,
    stake_amount: u64,
) -> Pubkey {
    let stake = Keypair::new();
    let lamports = get_stake_account_rent(&mut context.banks_client).await + stake_amount;

    let instructions = vec![
        system_instruction::create_account(
            &context.payer.pubkey(),
            &stake.pubkey(),
            lamports,
            std::mem::size_of::<StakeStateV2>() as u64,
            &id(),
        ),
        ixn::initialize(&stake.pubkey(), authorized, lockup),
    ];

    let transaction = Transaction::new_signed_with_payer(
        &instructions,
        Some(&context.payer.pubkey()),
        &[&context.payer, &stake],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    stake.pubkey()
}

pub async fn create_blank_stake_account(context: &mut ProgramTestContext) -> Pubkey {
    let stake = Keypair::new();
    create_blank_stake_account_from_keypair(context, &stake, false).await
}

pub async fn create_closed_stake_account(context: &mut ProgramTestContext) -> Pubkey {
    let stake = Keypair::new();
    create_blank_stake_account_from_keypair(context, &stake, true).await
}

pub async fn create_blank_stake_account_from_keypair(
    context: &mut ProgramTestContext,
    stake: &Keypair,
    is_closed: bool,
) -> Pubkey {
    // lamports in a "closed" account is arbitrary, a real one via split/merge/withdraw would have 0
    let lamports = get_stake_account_rent(&mut context.banks_client).await;

    let transaction = Transaction::new_signed_with_payer(
        &[system_instruction::create_account(
            &context.payer.pubkey(),
            &stake.pubkey(),
            lamports,
            if is_closed {
                0
            } else {
                StakeStateV2::size_of() as u64
            },
            &id(),
        )],
        Some(&context.payer.pubkey()),
        &[&context.payer, stake],
        context.last_blockhash,
    );

    context
        .banks_client
        .process_transaction(transaction)
        .await
        .unwrap();

    stake.pubkey()
}

pub async fn process_instruction<T: Signers + ?Sized>(
    context: &mut ProgramTestContext,
    instruction: &Instruction,
    additional_signers: &T,
) -> ProgramResult {
    let mut transaction = Transaction::new_with_payer(
        core::slice::from_ref(instruction),
        Some(&context.payer.pubkey()),
    );

    transaction.partial_sign(&[&context.payer], context.last_blockhash);
    transaction.sign(additional_signers, context.last_blockhash);

    match context.banks_client.process_transaction(transaction).await {
        Ok(_) => Ok(()),
        Err(e) => {
            // banks client error -> transaction error -> instruction error -> program error
            match e.unwrap() {
                TransactionError::InstructionError(_, e) => Err(e.try_into().unwrap()),
                TransactionError::InsufficientFundsForRent { .. } => {
                    Err(ProgramError::InsufficientFunds)
                }
                _ => panic!("couldnt convert {:?} to ProgramError", e),
            }
        }
    }
}

pub async fn process_instruction_test_missing_signers(
    context: &mut ProgramTestContext,
    instruction: &Instruction,
    additional_signers: &Vec<&Keypair>,
) {
    // remove every signer one by one and ensure we always fail
    for i in 0..instruction.accounts.len() {
        if instruction.accounts[i].is_signer {
            let mut instruction = instruction.clone();
            instruction.accounts[i].is_signer = false;
            let reduced_signers: Vec<_> = additional_signers
                .iter()
                .filter(|s| s.pubkey() != instruction.accounts[i].pubkey)
                .collect();

            let e = process_instruction(context, &instruction, &reduced_signers)
                .await
                .unwrap_err();
            assert_eq!(e, ProgramError::MissingRequiredSignature);
        }
    }

    // now make sure the instruction succeeds
    process_instruction(context, instruction, additional_signers)
        .await
        .unwrap();
}

#[tokio::test]
async fn program_test_stake_checked_instructions() {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let staker_keypair = Keypair::new();
    let withdrawer_keypair = Keypair::new();
    let authorized_keypair = Keypair::new();
    let seed_base_keypair = Keypair::new();
    let custodian_keypair = Keypair::new();

    let staker = staker_keypair.pubkey();
    let withdrawer = withdrawer_keypair.pubkey();
    let authorized = authorized_keypair.pubkey();
    let seed_base = seed_base_keypair.pubkey();
    let custodian = custodian_keypair.pubkey();

    let seed = "test seed";
    let seeded_address = Pubkey::create_with_seed(&seed_base, seed, &system_program::id()).unwrap();

    // Test InitializeChecked with non-signing withdrawer
    let stake = create_blank_stake_account(&mut context).await;
    let instruction = ixn::initialize_checked(&stake, &Authorized { staker, withdrawer });

    process_instruction_test_missing_signers(
        &mut context,
        &instruction,
        &vec![&withdrawer_keypair],
    )
    .await;

    // Test AuthorizeChecked with non-signing staker
    let stake =
        create_independent_stake_account(&mut context, &Authorized { staker, withdrawer }, 0).await;
    let instruction =
        ixn::authorize_checked(&stake, &staker, &authorized, StakeAuthorize::Staker, None);

    process_instruction_test_missing_signers(
        &mut context,
        &instruction,
        &vec![&staker_keypair, &authorized_keypair],
    )
    .await;

    // Test AuthorizeChecked with non-signing withdrawer
    let stake =
        create_independent_stake_account(&mut context, &Authorized { staker, withdrawer }, 0).await;
    let instruction = ixn::authorize_checked(
        &stake,
        &withdrawer,
        &authorized,
        StakeAuthorize::Withdrawer,
        None,
    );

    process_instruction_test_missing_signers(
        &mut context,
        &instruction,
        &vec![&withdrawer_keypair, &authorized_keypair],
    )
    .await;

    // Test AuthorizeCheckedWithSeed with non-signing authority
    for authority_type in [StakeAuthorize::Staker, StakeAuthorize::Withdrawer] {
        let stake =
            create_independent_stake_account(&mut context, &Authorized::auto(&seeded_address), 0)
                .await;
        let instruction = ixn::authorize_checked_with_seed(
            &stake,
            &seed_base,
            seed.to_string(),
            &system_program::id(),
            &authorized,
            authority_type,
            None,
        );

        process_instruction_test_missing_signers(
            &mut context,
            &instruction,
            &vec![&seed_base_keypair, &authorized_keypair],
        )
        .await;
    }

    // Test SetLockupChecked with non-signing lockup custodian
    let stake =
        create_independent_stake_account(&mut context, &Authorized { staker, withdrawer }, 0).await;
    let instruction = ixn::set_lockup_checked(
        &stake,
        &LockupArgs {
            unix_timestamp: None,
            epoch: Some(1),
            custodian: Some(custodian),
        },
        &withdrawer,
    );

    process_instruction_test_missing_signers(
        &mut context,
        &instruction,
        &vec![&withdrawer_keypair, &custodian_keypair],
    )
    .await;
}

#[tokio::test]
async fn program_test_stake_initialize() {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;

    let staker_keypair = Keypair::new();
    let withdrawer_keypair = Keypair::new();
    let custodian_keypair = Keypair::new();

    let staker = staker_keypair.pubkey();
    let withdrawer = withdrawer_keypair.pubkey();
    let custodian = custodian_keypair.pubkey();

    let authorized = Authorized { staker, withdrawer };

    let lockup = Lockup {
        epoch: 1,
        unix_timestamp: 0,
        custodian,
    };

    let stake = create_blank_stake_account(&mut context).await;
    let instruction = ixn::initialize(&stake, &authorized, &lockup);

    // should pass
    process_instruction(&mut context, &instruction, NO_SIGNERS)
        .await
        .unwrap();

    // check that we see what we expect
    let account = get_account(&mut context.banks_client, &stake).await;
    let stake_state: StakeStateV2 = bincode::deserialize(&account.data).unwrap();
    assert_eq!(
        stake_state,
        StakeStateV2::Initialized(Meta {
            authorized,
            rent_exempt_reserve,
            lockup,
        }),
    );

    // 2nd time fails, can't move it from anything other than uninit->init
    refresh_blockhash(&mut context).await;
    let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);

    // not enough balance for rent
    let stake = Pubkey::new_unique();
    let account = SolanaAccount {
        lamports: rent_exempt_reserve / 2,
        data: vec![0; StakeStateV2::size_of()],
        owner: id(),
        executable: false,
        rent_epoch: 1000,
    };
    context.set_account(&stake, &account.into());

    let instruction = ixn::initialize(&stake, &authorized, &lockup);
    let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InsufficientFunds);

    // incorrect account sizes
    let stake_keypair = Keypair::new();
    let stake = stake_keypair.pubkey();

    let instruction = system_instruction::create_account(
        &context.payer.pubkey(),
        &stake,
        rent_exempt_reserve * 2,
        StakeStateV2::size_of() as u64 + 1,
        &id(),
    );
    process_instruction(&mut context, &instruction, &vec![&stake_keypair])
        .await
        .unwrap();

    let instruction = ixn::initialize(&stake, &authorized, &lockup);
    let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);

    let stake_keypair = Keypair::new();
    let stake = stake_keypair.pubkey();

    let instruction = system_instruction::create_account(
        &context.payer.pubkey(),
        &stake,
        rent_exempt_reserve,
        StakeStateV2::size_of() as u64 - 1,
        &id(),
    );
    process_instruction(&mut context, &instruction, &vec![&stake_keypair])
        .await
        .unwrap();

    let instruction = ixn::initialize(&stake, &authorized, &lockup);
    let e = process_instruction(&mut context, &instruction, NO_SIGNERS)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);
}

#[tokio::test]
async fn program_test_authorize() {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;

    let stakers: [_; 3] = std::array::from_fn(|_| Keypair::new());
    let withdrawers: [_; 3] = std::array::from_fn(|_| Keypair::new());

    let stake_keypair = Keypair::new();
    let stake = create_blank_stake_account_from_keypair(&mut context, &stake_keypair, false).await;

    // authorize uninitialized fails
    for (authority, authority_type) in [
        (&stakers[0], StakeAuthorize::Staker),
        (&withdrawers[0], StakeAuthorize::Withdrawer),
    ] {
        let instruction = ixn::authorize(&stake, &stake, &authority.pubkey(), authority_type, None);
        let e = process_instruction(&mut context, &instruction, &vec![&stake_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::InvalidAccountData);
    }

    let authorized = Authorized {
        staker: stakers[0].pubkey(),
        withdrawer: withdrawers[0].pubkey(),
    };

    let instruction = ixn::initialize(&stake, &authorized, &Lockup::default());
    process_instruction(&mut context, &instruction, NO_SIGNERS)
        .await
        .unwrap();

    // changing authority works
    for (old_authority, new_authority, authority_type) in [
        (&stakers[0], &stakers[1], StakeAuthorize::Staker),
        (&withdrawers[0], &withdrawers[1], StakeAuthorize::Withdrawer),
    ] {
        let instruction = ixn::authorize(
            &stake,
            &old_authority.pubkey(),
            &new_authority.pubkey(),
            authority_type,
            None,
        );
        process_instruction_test_missing_signers(&mut context, &instruction, &vec![old_authority])
            .await;

        let (meta, _, _) = get_stake_account(&mut context.banks_client, &stake).await;
        let actual_authority = match authority_type {
            StakeAuthorize::Staker => meta.authorized.staker,
            StakeAuthorize::Withdrawer => meta.authorized.withdrawer,
        };
        assert_eq!(actual_authority, new_authority.pubkey());
    }

    // old authority no longer works
    for (old_authority, new_authority, authority_type) in [
        (&stakers[0], Pubkey::new_unique(), StakeAuthorize::Staker),
        (
            &withdrawers[0],
            Pubkey::new_unique(),
            StakeAuthorize::Withdrawer,
        ),
    ] {
        let instruction = ixn::authorize(
            &stake,
            &old_authority.pubkey(),
            &new_authority,
            authority_type,
            None,
        );
        let e = process_instruction(&mut context, &instruction, &vec![old_authority])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::MissingRequiredSignature);
    }

    // changing authority again works
    for (old_authority, new_authority, authority_type) in [
        (&stakers[1], &stakers[2], StakeAuthorize::Staker),
        (&withdrawers[1], &withdrawers[2], StakeAuthorize::Withdrawer),
    ] {
        let instruction = ixn::authorize(
            &stake,
            &old_authority.pubkey(),
            &new_authority.pubkey(),
            authority_type,
            None,
        );
        process_instruction_test_missing_signers(&mut context, &instruction, &vec![old_authority])
            .await;

        let (meta, _, _) = get_stake_account(&mut context.banks_client, &stake).await;
        let actual_authority = match authority_type {
            StakeAuthorize::Staker => meta.authorized.staker,
            StakeAuthorize::Withdrawer => meta.authorized.withdrawer,
        };
        assert_eq!(actual_authority, new_authority.pubkey());
    }

    // changing withdrawer using staker fails
    let instruction = ixn::authorize(
        &stake,
        &stakers[2].pubkey(),
        &Pubkey::new_unique(),
        StakeAuthorize::Withdrawer,
        None,
    );
    let e = process_instruction(&mut context, &instruction, &vec![&stakers[2]])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::MissingRequiredSignature);

    // changing staker using withdrawer is fine
    let instruction = ixn::authorize(
        &stake,
        &withdrawers[2].pubkey(),
        &stakers[0].pubkey(),
        StakeAuthorize::Staker,
        None,
    );
    process_instruction_test_missing_signers(&mut context, &instruction, &vec![&withdrawers[2]])
        .await;

    let (meta, _, _) = get_stake_account(&mut context.banks_client, &stake).await;
    assert_eq!(meta.authorized.staker, stakers[0].pubkey());

    // withdraw using staker fails
    for staker in stakers {
        let recipient = Pubkey::new_unique();
        let instruction = ixn::withdraw(
            &stake,
            &staker.pubkey(),
            &recipient,
            rent_exempt_reserve,
            None,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&staker])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::MissingRequiredSignature);
    }
}

#[tokio::test]
async fn program_test_stake_delegate() {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let vote_account2 = Keypair::new();
    create_vote(
        &mut context,
        &Keypair::new(),
        &Pubkey::new_unique(),
        &Pubkey::new_unique(),
        &vote_account2,
    )
    .await;

    let staker_keypair = Keypair::new();
    let withdrawer_keypair = Keypair::new();

    let staker = staker_keypair.pubkey();
    let withdrawer = withdrawer_keypair.pubkey();

    let authorized = Authorized { staker, withdrawer };

    let vote_state_credits = 100;
    context.increment_vote_account_credits(&accounts.vote_account.pubkey(), vote_state_credits);
    let minimum_delegation = get_minimum_delegation(&mut context).await;

    let stake =
        create_independent_stake_account(&mut context, &authorized, minimum_delegation).await;
    let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());

    process_instruction_test_missing_signers(&mut context, &instruction, &vec![&staker_keypair])
        .await;

    // verify that delegate() looks right
    let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
    let (_, stake_data, _) = get_stake_account(&mut context.banks_client, &stake).await;
    assert_eq!(
        stake_data.unwrap(),
        Stake {
            delegation: Delegation {
                voter_pubkey: accounts.vote_account.pubkey(),
                stake: minimum_delegation,
                activation_epoch: clock.epoch,
                deactivation_epoch: u64::MAX,
                ..Delegation::default()
            },
            credits_observed: vote_state_credits,
        }
    );

    // verify that delegate fails as stake is active and not deactivating
    advance_epoch(&mut context).await;
    let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, StakeError::TooSoonToRedelegate.into());

    // deactivate
    let instruction = ixn::deactivate_stake(&stake, &staker);
    process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap();

    // verify that delegate to a different vote account fails during deactivation
    let instruction = ixn::delegate_stake(&stake, &staker, &vote_account2.pubkey());
    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, StakeError::TooSoonToRedelegate.into());

    // verify that delegate succeeds to same vote account when stake is deactivating
    refresh_blockhash(&mut context).await;
    let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
    process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap();

    // verify that deactivation has been cleared
    let (_, stake_data, _) = get_stake_account(&mut context.banks_client, &stake).await;
    assert_eq!(stake_data.unwrap().delegation.deactivation_epoch, u64::MAX);

    // verify that delegate to a different vote account fails if stake is still
    // active
    let instruction = ixn::delegate_stake(&stake, &staker, &vote_account2.pubkey());
    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, StakeError::TooSoonToRedelegate.into());

    // delegate still fails after stake is fully activated; redelegate is not
    // supported
    advance_epoch(&mut context).await;
    let instruction = ixn::delegate_stake(&stake, &staker, &vote_account2.pubkey());
    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, StakeError::TooSoonToRedelegate.into());

    // delegate to spoofed vote account fails (not owned by vote program)
    let mut fake_vote_account =
        get_account(&mut context.banks_client, &accounts.vote_account.pubkey()).await;
    fake_vote_account.owner = Pubkey::new_unique();
    let fake_vote_address = Pubkey::new_unique();
    context.set_account(&fake_vote_address, &fake_vote_account.into());

    let stake =
        create_independent_stake_account(&mut context, &authorized, minimum_delegation).await;
    let instruction = ixn::delegate_stake(&stake, &staker, &fake_vote_address);

    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::IncorrectProgramId);

    // delegate stake program-owned non-stake account fails
    let rewards_pool_address = Pubkey::new_unique();
    let rewards_pool = SolanaAccount {
        lamports: get_stake_account_rent(&mut context.banks_client).await,
        data: bincode::serialize(&StakeStateV2::RewardsPool)
            .unwrap()
            .to_vec(),
        owner: id(),
        executable: false,
        rent_epoch: u64::MAX,
    };
    context.set_account(&rewards_pool_address, &rewards_pool.into());

    let instruction = ixn::delegate_stake(
        &rewards_pool_address,
        &staker,
        &accounts.vote_account.pubkey(),
    );

    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);
}

#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum StakeLifecycle {
    Uninitialized = 0,
    Initialized,
    Activating,
    Active,
    Deactivating,
    Deactive,
    Closed,
}
impl StakeLifecycle {
    // (stake, staker, withdrawer)
    pub async fn new_stake_account(
        self,
        context: &mut ProgramTestContext,
        vote_account: &Pubkey,
        staked_amount: u64,
    ) -> (Keypair, Keypair, Keypair) {
        let stake_keypair = Keypair::new();
        let staker_keypair = Keypair::new();
        let withdrawer_keypair = Keypair::new();

        self.new_stake_account_fully_specified(
            context,
            vote_account,
            staked_amount,
            &stake_keypair,
            &staker_keypair,
            &withdrawer_keypair,
            &Lockup::default(),
        )
        .await;

        (stake_keypair, staker_keypair, withdrawer_keypair)
    }

    #[allow(clippy::too_many_arguments)]
    pub async fn new_stake_account_fully_specified(
        self,
        context: &mut ProgramTestContext,
        vote_account: &Pubkey,
        staked_amount: u64,
        stake_keypair: &Keypair,
        staker_keypair: &Keypair,
        withdrawer_keypair: &Keypair,
        lockup: &Lockup,
    ) {
        let is_closed = self == StakeLifecycle::Closed;

        let stake =
            create_blank_stake_account_from_keypair(context, stake_keypair, is_closed).await;
        if staked_amount > 0 {
            transfer(context, &stake, staked_amount).await;
        }

        if is_closed {
            return;
        }

        let authorized = Authorized {
            staker: staker_keypair.pubkey(),
            withdrawer: withdrawer_keypair.pubkey(),
        };

        if self >= StakeLifecycle::Initialized {
            let instruction = ixn::initialize(&stake, &authorized, lockup);
            process_instruction(context, &instruction, NO_SIGNERS)
                .await
                .unwrap();
        }

        if self >= StakeLifecycle::Activating {
            let instruction = ixn::delegate_stake(&stake, &staker_keypair.pubkey(), vote_account);
            process_instruction(context, &instruction, &vec![staker_keypair])
                .await
                .unwrap();
        }

        if self >= StakeLifecycle::Active {
            advance_epoch(context).await;
            assert_eq!(
                get_effective_stake(&mut context.banks_client, &stake).await,
                staked_amount,
            );
        }

        if self >= StakeLifecycle::Deactivating {
            let instruction = ixn::deactivate_stake(&stake, &staker_keypair.pubkey());
            process_instruction(context, &instruction, &vec![staker_keypair])
                .await
                .unwrap();
        }

        if self == StakeLifecycle::Deactive {
            advance_epoch(context).await;
            assert_eq!(
                get_effective_stake(&mut context.banks_client, &stake).await,
                0,
            );
        }
    }

    pub fn minimum_delegation_enforced(&self) -> bool {
        match self {
            Self::Activating | Self::Active | Self::Deactivating => true,
            Self::Uninitialized | Self::Initialized | Self::Deactive | Self::Closed => false,
        }
    }
}

#[test_case(StakeLifecycle::Uninitialized; "uninitialized")]
#[test_case(StakeLifecycle::Initialized; "initialized")]
#[test_case(StakeLifecycle::Activating; "activating")]
#[test_case(StakeLifecycle::Active; "active")]
#[test_case(StakeLifecycle::Deactivating; "deactivating")]
#[test_case(StakeLifecycle::Deactive; "deactive")]
#[tokio::test]
async fn program_test_split(split_source_type: StakeLifecycle) {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;
    let minimum_delegation = get_minimum_delegation(&mut context).await;
    let staked_amount = minimum_delegation * 2;

    let (split_source_keypair, staker_keypair, _) = split_source_type
        .new_stake_account(&mut context, &accounts.vote_account.pubkey(), staked_amount)
        .await;

    let split_source = split_source_keypair.pubkey();
    let split_dest = create_blank_stake_account(&mut context).await;

    let signers = match split_source_type {
        StakeLifecycle::Uninitialized => vec![&split_source_keypair],
        _ => vec![&staker_keypair],
    };

    // fail, cannot split zero
    let instruction = &ixn::split(&split_source, &signers[0].pubkey(), 0, &split_dest)[2];
    let e = process_instruction(&mut context, instruction, &signers)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InsufficientFunds);

    // fail, split more than available (even if not active, would kick source out of
    // rent exemption)
    let instruction = &ixn::split(
        &split_source,
        &signers[0].pubkey(),
        staked_amount + 1,
        &split_dest,
    )[2];

    let e = process_instruction(&mut context, instruction, &signers)
        .await
        .unwrap_err();
    assert_eq!(
        e,
        if split_source_type.minimum_delegation_enforced() {
            StakeError::InsufficientDelegation.into()
        } else {
            ProgramError::InsufficientFunds
        }
    );

    // an active or transitioning stake account cannot have less than the minimum delegation
    // this is NOT dependent on the one sol minimum delegation feature
    // there was ALWAYS a minimum. it was one lamport!
    if split_source_type.minimum_delegation_enforced() {
        // underfunded destination fails
        let instruction = &ixn::split(
            &split_source,
            &signers[0].pubkey(),
            minimum_delegation - 1,
            &split_dest,
        )[2];

        let e = process_instruction(&mut context, instruction, &signers)
            .await
            .unwrap_err();
        assert_eq!(e, StakeError::InsufficientDelegation.into());

        // underfunded source fails
        let instruction = &ixn::split(
            &split_source,
            &signers[0].pubkey(),
            minimum_delegation + 1,
            &split_dest,
        )[2];

        let e = process_instruction(&mut context, instruction, &signers)
            .await
            .unwrap_err();
        assert_eq!(e, StakeError::InsufficientDelegation.into());
    }

    // split to non-owned account fails
    let mut fake_split_dest_account = get_account(&mut context.banks_client, &split_dest).await;
    fake_split_dest_account.owner = Pubkey::new_unique();
    let fake_split_dest = Pubkey::new_unique();
    context.set_account(&fake_split_dest, &fake_split_dest_account.into());

    let instruction = &ixn::split(
        &split_source,
        &signers[0].pubkey(),
        staked_amount / 2,
        &fake_split_dest,
    )[2];

    let e = process_instruction(&mut context, instruction, &signers)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountOwner);

    // success
    let instruction = &ixn::split(
        &split_source,
        &signers[0].pubkey(),
        staked_amount / 2,
        &split_dest,
    )[2];
    process_instruction_test_missing_signers(&mut context, instruction, &signers).await;

    // source lost split amount
    let source_lamports = get_account(&mut context.banks_client, &split_source)
        .await
        .lamports;
    assert_eq!(source_lamports, staked_amount / 2 + rent_exempt_reserve);

    // destination gained split amount
    let dest_lamports = get_account(&mut context.banks_client, &split_dest)
        .await
        .lamports;
    assert_eq!(dest_lamports, staked_amount / 2 + rent_exempt_reserve);

    // destination meta has been set properly if ever delegated
    if split_source_type >= StakeLifecycle::Initialized {
        let (source_meta, source_stake, _) =
            get_stake_account(&mut context.banks_client, &split_source).await;
        let (dest_meta, dest_stake, _) =
            get_stake_account(&mut context.banks_client, &split_dest).await;
        assert_eq!(dest_meta, source_meta);

        // delegations are set properly if activating or active
        if split_source_type >= StakeLifecycle::Activating
            && split_source_type < StakeLifecycle::Deactive
        {
            assert_eq!(source_stake.unwrap().delegation.stake, staked_amount / 2);
            assert_eq!(dest_stake.unwrap().delegation.stake, staked_amount / 2);
        }
    }

    // nothing has been deactivated if active
    if split_source_type >= StakeLifecycle::Active && split_source_type < StakeLifecycle::Deactive {
        assert_eq!(
            get_effective_stake(&mut context.banks_client, &split_source).await,
            staked_amount / 2,
        );

        assert_eq!(
            get_effective_stake(&mut context.banks_client, &split_dest).await,
            staked_amount / 2,
        );
    }
}

#[test_case(StakeLifecycle::Uninitialized; "uninitialized")]
#[test_case(StakeLifecycle::Initialized; "initialized")]
#[test_case(StakeLifecycle::Activating; "activating")]
#[test_case(StakeLifecycle::Active; "active")]
#[test_case(StakeLifecycle::Deactivating; "deactivating")]
#[test_case(StakeLifecycle::Deactive; "deactive")]
#[test_case(StakeLifecycle::Closed; "closed")]
#[tokio::test]
async fn program_test_withdraw_stake(withdraw_source_type: StakeLifecycle) {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let stake_rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;
    let minimum_delegation = get_minimum_delegation(&mut context).await;
    let staked_amount = minimum_delegation;

    let wallet_rent_exempt_reserve = context
        .banks_client
        .get_rent()
        .await
        .unwrap()
        .minimum_balance(0);

    let (withdraw_source_keypair, _, withdrawer_keypair) = withdraw_source_type
        .new_stake_account(&mut context, &accounts.vote_account.pubkey(), staked_amount)
        .await;
    let withdraw_source = withdraw_source_keypair.pubkey();

    let recipient = Pubkey::new_unique();
    transfer(&mut context, &recipient, wallet_rent_exempt_reserve).await;

    let signers = match withdraw_source_type {
        StakeLifecycle::Uninitialized | StakeLifecycle::Closed => vec![&withdraw_source_keypair],
        _ => vec![&withdrawer_keypair],
    };

    // withdraw that would end rent-exemption always fails
    let rent_spillover = if withdraw_source_type == StakeLifecycle::Closed {
        stake_rent_exempt_reserve - Rent::default().minimum_balance(0) + 1
    } else {
        1
    };

    let instruction = ixn::withdraw(
        &withdraw_source,
        &signers[0].pubkey(),
        &recipient,
        staked_amount + rent_spillover,
        None,
    );
    let e = process_instruction(&mut context, &instruction, &signers)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InsufficientFunds);

    if withdraw_source_type.minimum_delegation_enforced() {
        // withdraw active or activating stake fails
        let instruction = ixn::withdraw(
            &withdraw_source,
            &signers[0].pubkey(),
            &recipient,
            staked_amount,
            None,
        );
        let e = process_instruction(&mut context, &instruction, &signers)
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::InsufficientFunds);

        // grant rewards
        let reward_amount = 10;
        transfer(&mut context, &withdraw_source, reward_amount).await;

        // withdraw in excess of rewards is not allowed
        let instruction = ixn::withdraw(
            &withdraw_source,
            &signers[0].pubkey(),
            &recipient,
            reward_amount + 1,
            None,
        );
        let e = process_instruction(&mut context, &instruction, &signers)
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::InsufficientFunds);

        // withdraw rewards is allowed
        let instruction = ixn::withdraw(
            &withdraw_source,
            &signers[0].pubkey(),
            &recipient,
            reward_amount,
            None,
        );
        process_instruction_test_missing_signers(&mut context, &instruction, &signers).await;

        let recipient_lamports = get_account(&mut context.banks_client, &recipient)
            .await
            .lamports;
        assert_eq!(
            recipient_lamports,
            reward_amount + wallet_rent_exempt_reserve,
        );
    } else {
        // withdraw that leaves rent behind is allowed
        let instruction = ixn::withdraw(
            &withdraw_source,
            &signers[0].pubkey(),
            &recipient,
            staked_amount,
            None,
        );
        process_instruction_test_missing_signers(&mut context, &instruction, &signers).await;

        let recipient_lamports = get_account(&mut context.banks_client, &recipient)
            .await
            .lamports;
        assert_eq!(
            recipient_lamports,
            staked_amount + wallet_rent_exempt_reserve,
        );

        // full withdraw is allowed
        refresh_blockhash(&mut context).await;
        transfer(&mut context, &withdraw_source, staked_amount).await;

        let recipient = Pubkey::new_unique();
        transfer(&mut context, &recipient, wallet_rent_exempt_reserve).await;

        let instruction = ixn::withdraw(
            &withdraw_source,
            &signers[0].pubkey(),
            &recipient,
            staked_amount + stake_rent_exempt_reserve,
            None,
        );
        process_instruction_test_missing_signers(&mut context, &instruction, &signers).await;

        let recipient_lamports = get_account(&mut context.banks_client, &recipient)
            .await
            .lamports;
        assert_eq!(
            recipient_lamports,
            staked_amount + stake_rent_exempt_reserve + wallet_rent_exempt_reserve,
        );
    }

    // withdraw from program-owned non-stake not allowed
    let rewards_pool_address = Pubkey::new_unique();
    let rewards_pool = SolanaAccount {
        lamports: get_stake_account_rent(&mut context.banks_client).await + staked_amount,
        data: bincode::serialize(&StakeStateV2::RewardsPool)
            .unwrap()
            .to_vec(),
        owner: id(),
        executable: false,
        rent_epoch: u64::MAX,
    };
    context.set_account(&rewards_pool_address, &rewards_pool.into());

    let instruction = ixn::withdraw(
        &rewards_pool_address,
        &signers[0].pubkey(),
        &recipient,
        staked_amount,
        None,
    );
    let e = process_instruction(&mut context, &instruction, &signers)
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);
}

#[test_case(false; "activating")]
#[test_case(true; "active")]
#[tokio::test]
async fn program_test_deactivate(activate: bool) {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let minimum_delegation = get_minimum_delegation(&mut context).await;

    let staker_keypair = Keypair::new();
    let withdrawer_keypair = Keypair::new();

    let staker = staker_keypair.pubkey();
    let withdrawer = withdrawer_keypair.pubkey();

    let authorized = Authorized { staker, withdrawer };

    let stake =
        create_independent_stake_account(&mut context, &authorized, minimum_delegation).await;

    // deactivating an undelegated account fails
    let instruction = ixn::deactivate_stake(&stake, &staker);
    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);

    // delegate
    let instruction = ixn::delegate_stake(&stake, &staker, &accounts.vote_account.pubkey());
    process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap();

    if activate {
        advance_epoch(&mut context).await;
    } else {
        refresh_blockhash(&mut context).await;
    }

    // deactivate with withdrawer fails
    let instruction = ixn::deactivate_stake(&stake, &withdrawer);
    let e = process_instruction(&mut context, &instruction, &vec![&withdrawer_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::MissingRequiredSignature);

    // deactivate succeeds
    let instruction = ixn::deactivate_stake(&stake, &staker);
    process_instruction_test_missing_signers(&mut context, &instruction, &vec![&staker_keypair])
        .await;

    let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
    let (_, stake_data, _) = get_stake_account(&mut context.banks_client, &stake).await;
    assert_eq!(
        stake_data.unwrap().delegation.deactivation_epoch,
        clock.epoch
    );

    // deactivate again fails
    refresh_blockhash(&mut context).await;

    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, StakeError::AlreadyDeactivated.into());

    advance_epoch(&mut context).await;

    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, StakeError::AlreadyDeactivated.into());
}

#[test_matrix(
    [StakeLifecycle::Uninitialized, StakeLifecycle::Initialized, StakeLifecycle::Activating,
     StakeLifecycle::Active, StakeLifecycle::Deactivating, StakeLifecycle::Deactive],
    [StakeLifecycle::Uninitialized, StakeLifecycle::Initialized, StakeLifecycle::Activating,
     StakeLifecycle::Active, StakeLifecycle::Deactivating, StakeLifecycle::Deactive]
)]
#[tokio::test]
async fn program_test_merge(merge_source_type: StakeLifecycle, merge_dest_type: StakeLifecycle) {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;
    let minimum_delegation = get_minimum_delegation(&mut context).await;
    let staked_amount = minimum_delegation;

    // stake accounts can be merged unconditionally:
    // * inactive and inactive
    // * inactive into activating
    // can be merged IF vote pubkey and credits match:
    // * active and active
    // * activating and activating, IF activating in the same epoch
    // in all cases, authorized and lockup also must match
    // uninitialized stakes cannot be merged at all
    let is_merge_allowed_by_type = match (merge_source_type, merge_dest_type) {
        // inactive and inactive
        (StakeLifecycle::Initialized, StakeLifecycle::Initialized)
        | (StakeLifecycle::Initialized, StakeLifecycle::Deactive)
        | (StakeLifecycle::Deactive, StakeLifecycle::Initialized)
        | (StakeLifecycle::Deactive, StakeLifecycle::Deactive) => true,

        // activating into inactive is also allowed although this isnt clear from docs
        (StakeLifecycle::Activating, StakeLifecycle::Initialized)
        | (StakeLifecycle::Activating, StakeLifecycle::Deactive) => true,

        // inactive into activating
        (StakeLifecycle::Initialized, StakeLifecycle::Activating)
        | (StakeLifecycle::Deactive, StakeLifecycle::Activating) => true,

        // active and active
        (StakeLifecycle::Active, StakeLifecycle::Active) => true,

        // activating and activating
        (StakeLifecycle::Activating, StakeLifecycle::Activating) => true,

        // better luck next time
        _ => false,
    };

    // create source first
    let (merge_source_keypair, _, _) = merge_source_type
        .new_stake_account(&mut context, &accounts.vote_account.pubkey(), staked_amount)
        .await;
    let merge_source = merge_source_keypair.pubkey();

    // retrieve its data
    let mut source_account = get_account(&mut context.banks_client, &merge_source).await;
    let mut source_stake_state: StakeStateV2 = bincode::deserialize(&source_account.data).unwrap();

    // create dest. this may mess source up if its in a transient state, but its
    // fine
    let (merge_dest_keypair, staker_keypair, withdrawer_keypair) = merge_dest_type
        .new_stake_account(&mut context, &accounts.vote_account.pubkey(), staked_amount)
        .await;
    let merge_dest = merge_dest_keypair.pubkey();

    // now we change source authorized to match dest
    // we can also true up the epoch if source should have been transient
    let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
    match &mut source_stake_state {
        StakeStateV2::Initialized(ref mut meta) => {
            meta.authorized.staker = staker_keypair.pubkey();
            meta.authorized.withdrawer = withdrawer_keypair.pubkey();
        }
        StakeStateV2::Stake(ref mut meta, ref mut stake, _) => {
            meta.authorized.staker = staker_keypair.pubkey();
            meta.authorized.withdrawer = withdrawer_keypair.pubkey();

            match merge_source_type {
                StakeLifecycle::Activating => stake.delegation.activation_epoch = clock.epoch,
                StakeLifecycle::Deactivating => stake.delegation.deactivation_epoch = clock.epoch,
                _ => (),
            }
        }
        _ => (),
    }

    // and store
    source_account.data = bincode::serialize(&source_stake_state).unwrap();
    context.set_account(&merge_source, &source_account.into());

    // attempt to merge
    let instruction = ixn::merge(&merge_dest, &merge_source, &staker_keypair.pubkey())
        .into_iter()
        .next()
        .unwrap();

    // failure can result in various different errors... dont worry about it for now
    if is_merge_allowed_by_type {
        process_instruction_test_missing_signers(
            &mut context,
            &instruction,
            &vec![&staker_keypair],
        )
        .await;

        let dest_lamports = get_account(&mut context.banks_client, &merge_dest)
            .await
            .lamports;
        assert_eq!(dest_lamports, staked_amount * 2 + rent_exempt_reserve * 2);
    } else {
        process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
    }
}

#[test_matrix(
    [StakeLifecycle::Initialized, StakeLifecycle::Activating, StakeLifecycle::Active,
     StakeLifecycle::Deactivating, StakeLifecycle::Deactive],
    [StakeLifecycle::Initialized, StakeLifecycle::Activating, StakeLifecycle::Active,
     StakeLifecycle::Deactivating, StakeLifecycle::Deactive],
    [false, true],
    [false, true]
)]
#[tokio::test]
async fn program_test_move_stake(
    move_source_type: StakeLifecycle,
    move_dest_type: StakeLifecycle,
    full_move: bool,
    has_lockup: bool,
) {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;
    let minimum_delegation = get_minimum_delegation(&mut context).await;

    // source has 2x minimum so we can easily test an unfunded destination
    let source_staked_amount = minimum_delegation * 2;

    // this is the amount of *staked* lamports for test checks
    // destinations may have excess lamports but these are *never* activated by move
    let dest_staked_amount = if move_dest_type == StakeLifecycle::Active {
        minimum_delegation
    } else {
        0
    };

    // test with and without lockup. both of these cases pass, we test failures
    // elsewhere
    let lockup = if has_lockup {
        let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
        let lockup = Lockup {
            unix_timestamp: 0,
            epoch: clock.epoch + 100,
            custodian: Pubkey::new_unique(),
        };

        assert!(lockup.is_in_force(&clock, None));
        lockup
    } else {
        Lockup::default()
    };

    // we put an extra minimum in every account, unstaked, to test that no new
    // lamports activate name them here so our asserts are readable
    let source_excess = minimum_delegation;
    let dest_excess = minimum_delegation;

    let move_source_keypair = Keypair::new();
    let move_dest_keypair = Keypair::new();
    let staker_keypair = Keypair::new();
    let withdrawer_keypair = Keypair::new();

    // create source stake
    move_source_type
        .new_stake_account_fully_specified(
            &mut context,
            &accounts.vote_account.pubkey(),
            source_staked_amount,
            &move_source_keypair,
            &staker_keypair,
            &withdrawer_keypair,
            &lockup,
        )
        .await;
    let move_source = move_source_keypair.pubkey();
    let mut source_account = get_account(&mut context.banks_client, &move_source).await;
    let mut source_stake_state: StakeStateV2 = bincode::deserialize(&source_account.data).unwrap();

    // create dest stake with same authorities
    move_dest_type
        .new_stake_account_fully_specified(
            &mut context,
            &accounts.vote_account.pubkey(),
            minimum_delegation,
            &move_dest_keypair,
            &staker_keypair,
            &withdrawer_keypair,
            &lockup,
        )
        .await;
    let move_dest = move_dest_keypair.pubkey();

    // true up source epoch if transient
    if move_source_type == StakeLifecycle::Activating
        || move_source_type == StakeLifecycle::Deactivating
    {
        let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
        if let StakeStateV2::Stake(_, ref mut stake, _) = &mut source_stake_state {
            match move_source_type {
                StakeLifecycle::Activating => stake.delegation.activation_epoch = clock.epoch,
                StakeLifecycle::Deactivating => stake.delegation.deactivation_epoch = clock.epoch,
                _ => (),
            }
        }

        source_account.data = bincode::serialize(&source_stake_state).unwrap();
        context.set_account(&move_source, &source_account.into());
    }

    // our inactive accounts have extra lamports, lets not let active feel left out
    if move_dest_type == StakeLifecycle::Active {
        transfer(&mut context, &move_dest, dest_excess).await;
    }

    // hey why not spread the love around to everyone
    transfer(&mut context, &move_source, source_excess).await;

    // alright first things first, clear out all the state failures
    match (move_source_type, move_dest_type) {
        // valid
        (StakeLifecycle::Active, StakeLifecycle::Initialized)
        | (StakeLifecycle::Active, StakeLifecycle::Active)
        | (StakeLifecycle::Active, StakeLifecycle::Deactive) => (),
        // invalid! get outta my test
        _ => {
            let instruction = ixn::move_stake(
                &move_source,
                &move_dest,
                &staker_keypair.pubkey(),
                if full_move {
                    source_staked_amount
                } else {
                    minimum_delegation
                },
            );

            // this is InvalidAccountData sometimes and Custom(5) sometimes but i dont care
            process_instruction(&mut context, &instruction, &vec![&staker_keypair])
                .await
                .unwrap_err();
            return;
        }
    }

    // the below checks are conceptually incoherent with a 1 lamport minimum
    // the undershoot fails successfully (but because its a zero move, not because
    // the destination ends underfunded) then the second one succeeds failedly
    // (because its a full move, so the "underfunded" source is actually closed)
    if minimum_delegation > 1 {
        // first for inactive accounts lets undershoot and fail for underfunded dest
        if move_dest_type != StakeLifecycle::Active {
            let instruction = ixn::move_stake(
                &move_source,
                &move_dest,
                &staker_keypair.pubkey(),
                minimum_delegation - 1,
            );

            let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
                .await
                .unwrap_err();
            assert_eq!(e, ProgramError::InvalidArgument);
        }

        // now lets overshoot and fail for underfunded source
        let instruction = ixn::move_stake(
            &move_source,
            &move_dest,
            &staker_keypair.pubkey(),
            minimum_delegation + 1,
        );

        let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::InvalidArgument);
    }

    // now we do it juuust right
    let instruction = ixn::move_stake(
        &move_source,
        &move_dest,
        &staker_keypair.pubkey(),
        if full_move {
            source_staked_amount
        } else {
            minimum_delegation
        },
    );

    process_instruction_test_missing_signers(&mut context, &instruction, &vec![&staker_keypair])
        .await;

    if full_move {
        let (_, option_source_stake, source_lamports) =
            get_stake_account(&mut context.banks_client, &move_source).await;

        // source is deactivated and rent/excess stay behind
        assert!(option_source_stake.is_none());
        assert_eq!(source_lamports, source_excess + rent_exempt_reserve);

        let (_, Some(dest_stake), dest_lamports) =
            get_stake_account(&mut context.banks_client, &move_dest).await
        else {
            panic!("dest should be active")
        };
        let dest_effective_stake = get_effective_stake(&mut context.banks_client, &move_dest).await;

        // dest captured the entire source delegation, kept its rent/excess, didnt
        // activate its excess
        assert_eq!(
            dest_stake.delegation.stake,
            source_staked_amount + dest_staked_amount
        );
        assert_eq!(dest_effective_stake, dest_stake.delegation.stake);
        assert_eq!(
            dest_lamports,
            dest_effective_stake + dest_excess + rent_exempt_reserve
        );
    } else {
        let (_, Some(source_stake), source_lamports) =
            get_stake_account(&mut context.banks_client, &move_source).await
        else {
            panic!("source should be active")
        };
        let source_effective_stake =
            get_effective_stake(&mut context.banks_client, &move_source).await;

        // half of source delegation moved over, excess stayed behind
        assert_eq!(source_stake.delegation.stake, source_staked_amount / 2);
        assert_eq!(source_effective_stake, source_stake.delegation.stake);
        assert_eq!(
            source_lamports,
            source_effective_stake + source_excess + rent_exempt_reserve
        );

        let (_, Some(dest_stake), dest_lamports) =
            get_stake_account(&mut context.banks_client, &move_dest).await
        else {
            panic!("dest should be active")
        };
        let dest_effective_stake = get_effective_stake(&mut context.banks_client, &move_dest).await;

        // dest mirrors our observations
        assert_eq!(
            dest_stake.delegation.stake,
            source_staked_amount / 2 + dest_staked_amount
        );
        assert_eq!(dest_effective_stake, dest_stake.delegation.stake);
        assert_eq!(
            dest_lamports,
            dest_effective_stake + dest_excess + rent_exempt_reserve
        );
    }
}

#[test_matrix(
    [StakeLifecycle::Initialized, StakeLifecycle::Activating, StakeLifecycle::Active,
     StakeLifecycle::Deactivating, StakeLifecycle::Deactive],
    [StakeLifecycle::Initialized, StakeLifecycle::Activating, StakeLifecycle::Active,
     StakeLifecycle::Deactivating, StakeLifecycle::Deactive],
    [false, true],
    [false, true]
)]
#[tokio::test]
async fn program_test_move_lamports(
    move_source_type: StakeLifecycle,
    move_dest_type: StakeLifecycle,
    different_votes: bool,
    has_lockup: bool,
) {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let rent_exempt_reserve = get_stake_account_rent(&mut context.banks_client).await;
    let minimum_delegation = get_minimum_delegation(&mut context).await;

    // put minimum in both accounts if theyre active
    let source_staked_amount = if move_source_type == StakeLifecycle::Active {
        minimum_delegation
    } else {
        0
    };

    let dest_staked_amount = if move_dest_type == StakeLifecycle::Active {
        minimum_delegation
    } else {
        0
    };

    // test with and without lockup. both of these cases pass, we test failures
    // elsewhere
    let lockup = if has_lockup {
        let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
        let lockup = Lockup {
            unix_timestamp: 0,
            epoch: clock.epoch + 100,
            custodian: Pubkey::new_unique(),
        };

        assert!(lockup.is_in_force(&clock, None));
        lockup
    } else {
        Lockup::default()
    };

    // we put an extra minimum in every account, unstaked, to test moving them
    let source_excess = minimum_delegation;
    let dest_excess = minimum_delegation;

    let move_source_keypair = Keypair::new();
    let move_dest_keypair = Keypair::new();
    let staker_keypair = Keypair::new();
    let withdrawer_keypair = Keypair::new();

    // make a separate vote account if needed
    let dest_vote_account = if different_votes {
        let vote_account = Keypair::new();
        create_vote(
            &mut context,
            &Keypair::new(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &vote_account,
        )
        .await;

        vote_account.pubkey()
    } else {
        accounts.vote_account.pubkey()
    };

    // create source stake
    move_source_type
        .new_stake_account_fully_specified(
            &mut context,
            &accounts.vote_account.pubkey(),
            minimum_delegation,
            &move_source_keypair,
            &staker_keypair,
            &withdrawer_keypair,
            &lockup,
        )
        .await;
    let move_source = move_source_keypair.pubkey();
    let mut source_account = get_account(&mut context.banks_client, &move_source).await;
    let mut source_stake_state: StakeStateV2 = bincode::deserialize(&source_account.data).unwrap();

    // create dest stake with same authorities
    move_dest_type
        .new_stake_account_fully_specified(
            &mut context,
            &dest_vote_account,
            minimum_delegation,
            &move_dest_keypair,
            &staker_keypair,
            &withdrawer_keypair,
            &lockup,
        )
        .await;
    let move_dest = move_dest_keypair.pubkey();

    // true up source epoch if transient
    if move_source_type == StakeLifecycle::Activating
        || move_source_type == StakeLifecycle::Deactivating
    {
        let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
        if let StakeStateV2::Stake(_, ref mut stake, _) = &mut source_stake_state {
            match move_source_type {
                StakeLifecycle::Activating => stake.delegation.activation_epoch = clock.epoch,
                StakeLifecycle::Deactivating => stake.delegation.deactivation_epoch = clock.epoch,
                _ => (),
            }
        }

        source_account.data = bincode::serialize(&source_stake_state).unwrap();
        context.set_account(&move_source, &source_account.into());
    }

    // if we activated the initial amount we need to top up with the test lamports
    if move_source_type == StakeLifecycle::Active {
        transfer(&mut context, &move_source, source_excess).await;
    }
    if move_dest_type == StakeLifecycle::Active {
        transfer(&mut context, &move_dest, dest_excess).await;
    }

    // clear out state failures
    if move_source_type == StakeLifecycle::Activating
        || move_source_type == StakeLifecycle::Deactivating
        || move_dest_type == StakeLifecycle::Deactivating
    {
        let instruction = ixn::move_lamports(
            &move_source,
            &move_dest,
            &staker_keypair.pubkey(),
            source_excess,
        );

        process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        return;
    }

    // overshoot and fail for underfunded source
    let instruction = ixn::move_lamports(
        &move_source,
        &move_dest,
        &staker_keypair.pubkey(),
        source_excess + 1,
    );

    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidArgument);

    let (_, _, before_source_lamports) =
        get_stake_account(&mut context.banks_client, &move_source).await;
    let (_, _, before_dest_lamports) =
        get_stake_account(&mut context.banks_client, &move_dest).await;

    // now properly move the full excess
    let instruction = ixn::move_lamports(
        &move_source,
        &move_dest,
        &staker_keypair.pubkey(),
        source_excess,
    );

    process_instruction_test_missing_signers(&mut context, &instruction, &vec![&staker_keypair])
        .await;

    let (_, _, after_source_lamports) =
        get_stake_account(&mut context.banks_client, &move_source).await;
    let source_effective_stake = get_effective_stake(&mut context.banks_client, &move_source).await;

    // source activation didnt change
    assert_eq!(source_effective_stake, source_staked_amount);

    // source lamports are right
    assert_eq!(
        after_source_lamports,
        before_source_lamports - minimum_delegation
    );
    assert_eq!(
        after_source_lamports,
        source_effective_stake + rent_exempt_reserve
    );

    let (_, _, after_dest_lamports) =
        get_stake_account(&mut context.banks_client, &move_dest).await;
    let dest_effective_stake = get_effective_stake(&mut context.banks_client, &move_dest).await;

    // dest activation didnt change
    assert_eq!(dest_effective_stake, dest_staked_amount);

    // dest lamports are right
    assert_eq!(
        after_dest_lamports,
        before_dest_lamports + minimum_delegation
    );
    assert_eq!(
        after_dest_lamports,
        dest_effective_stake + rent_exempt_reserve + source_excess + dest_excess
    );
}

#[test_matrix(
    [(StakeLifecycle::Active, StakeLifecycle::Uninitialized),
     (StakeLifecycle::Uninitialized, StakeLifecycle::Initialized),
     (StakeLifecycle::Uninitialized, StakeLifecycle::Uninitialized)],
    [false, true]
)]
#[tokio::test]
async fn program_test_move_uninitialized_fail(
    move_types: (StakeLifecycle, StakeLifecycle),
    move_lamports: bool,
) {
    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let minimum_delegation = get_minimum_delegation(&mut context).await;
    let source_staked_amount = minimum_delegation * 2;

    let (move_source_type, move_dest_type) = move_types;

    let (move_source_keypair, staker_keypair, withdrawer_keypair) = move_source_type
        .new_stake_account(
            &mut context,
            &accounts.vote_account.pubkey(),
            source_staked_amount,
        )
        .await;
    let move_source = move_source_keypair.pubkey();

    let move_dest_keypair = Keypair::new();
    move_dest_type
        .new_stake_account_fully_specified(
            &mut context,
            &accounts.vote_account.pubkey(),
            0,
            &move_dest_keypair,
            &staker_keypair,
            &withdrawer_keypair,
            &Lockup::default(),
        )
        .await;
    let move_dest = move_dest_keypair.pubkey();

    let source_signer = if move_source_type == StakeLifecycle::Uninitialized {
        &move_source_keypair
    } else {
        &staker_keypair
    };

    let instruction = if move_lamports {
        ixn::move_lamports(
            &move_source,
            &move_dest,
            &source_signer.pubkey(),
            minimum_delegation,
        )
    } else {
        ixn::move_stake(
            &move_source,
            &move_dest,
            &source_signer.pubkey(),
            minimum_delegation,
        )
    };

    let e = process_instruction(&mut context, &instruction, &vec![source_signer])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidAccountData);
}

#[test_matrix(
    [StakeLifecycle::Initialized, StakeLifecycle::Active, StakeLifecycle::Deactive],
    [StakeLifecycle::Initialized, StakeLifecycle::Activating, StakeLifecycle::Active, StakeLifecycle::Deactive],
    [false, true]
)]
#[tokio::test]
async fn program_test_move_general_fail(
    move_source_type: StakeLifecycle,
    move_dest_type: StakeLifecycle,
    move_lamports: bool,
) {
    // the test_matrix includes all valid source/dest combinations for MoveLamports
    // we dont test invalid combinations because they would fail regardless of the
    // fail cases we test here valid source/dest for MoveStake are a strict
    // subset of MoveLamports source must be active, and dest must be active or
    // inactive. so we skip the additional invalid MoveStake cases
    if !move_lamports
        && (move_source_type != StakeLifecycle::Active
            || move_dest_type == StakeLifecycle::Activating)
    {
        return;
    }

    let mut context = program_test().start_with_context().await;
    let accounts = Accounts::default();
    accounts.initialize(&mut context).await;

    let minimum_delegation = get_minimum_delegation(&mut context).await;
    let source_staked_amount = minimum_delegation * 2;

    let in_force_lockup = {
        let clock = context.banks_client.get_sysvar::<Clock>().await.unwrap();
        Lockup {
            unix_timestamp: 0,
            epoch: clock.epoch + 1_000_000,
            custodian: Pubkey::new_unique(),
        }
    };

    let mk_ixn = if move_lamports {
        ixn::move_lamports
    } else {
        ixn::move_stake
    };

    // we can reuse source but will need a lot of dest
    let (move_source_keypair, staker_keypair, withdrawer_keypair) = move_source_type
        .new_stake_account(
            &mut context,
            &accounts.vote_account.pubkey(),
            source_staked_amount,
        )
        .await;
    let move_source = move_source_keypair.pubkey();
    transfer(&mut context, &move_source, minimum_delegation).await;

    // self-move fails
    let instruction = mk_ixn(
        &move_source,
        &move_source,
        &staker_keypair.pubkey(),
        minimum_delegation,
    );
    let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
        .await
        .unwrap_err();
    assert_eq!(e, ProgramError::InvalidInstructionData);

    // first we make a "normal" move dest
    {
        let move_dest_keypair = Keypair::new();
        move_dest_type
            .new_stake_account_fully_specified(
                &mut context,
                &accounts.vote_account.pubkey(),
                minimum_delegation,
                &move_dest_keypair,
                &staker_keypair,
                &withdrawer_keypair,
                &Lockup::default(),
            )
            .await;
        let move_dest = move_dest_keypair.pubkey();

        // zero move fails
        let instruction = mk_ixn(&move_source, &move_dest, &staker_keypair.pubkey(), 0);
        let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::InvalidArgument);

        // sign with withdrawer fails
        let instruction = mk_ixn(
            &move_source,
            &move_dest,
            &withdrawer_keypair.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&withdrawer_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::MissingRequiredSignature);

        // good place to test source lockup
        let move_locked_source_keypair = Keypair::new();
        move_source_type
            .new_stake_account_fully_specified(
                &mut context,
                &accounts.vote_account.pubkey(),
                source_staked_amount,
                &move_locked_source_keypair,
                &staker_keypair,
                &withdrawer_keypair,
                &in_force_lockup,
            )
            .await;
        let move_locked_source = move_locked_source_keypair.pubkey();
        transfer(&mut context, &move_locked_source, minimum_delegation).await;

        let instruction = mk_ixn(
            &move_locked_source,
            &move_dest,
            &staker_keypair.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, StakeError::MergeMismatch.into());
    }

    // staker mismatch
    {
        let move_dest_keypair = Keypair::new();
        let throwaway = Keypair::new();
        move_dest_type
            .new_stake_account_fully_specified(
                &mut context,
                &accounts.vote_account.pubkey(),
                minimum_delegation,
                &move_dest_keypair,
                &throwaway,
                &withdrawer_keypair,
                &Lockup::default(),
            )
            .await;
        let move_dest = move_dest_keypair.pubkey();

        let instruction = mk_ixn(
            &move_source,
            &move_dest,
            &staker_keypair.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, StakeError::MergeMismatch.into());

        let instruction = mk_ixn(
            &move_source,
            &move_dest,
            &throwaway.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&throwaway])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::MissingRequiredSignature);
    }

    // withdrawer mismatch
    {
        let move_dest_keypair = Keypair::new();
        let throwaway = Keypair::new();
        move_dest_type
            .new_stake_account_fully_specified(
                &mut context,
                &accounts.vote_account.pubkey(),
                minimum_delegation,
                &move_dest_keypair,
                &staker_keypair,
                &throwaway,
                &Lockup::default(),
            )
            .await;
        let move_dest = move_dest_keypair.pubkey();

        let instruction = mk_ixn(
            &move_source,
            &move_dest,
            &staker_keypair.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, StakeError::MergeMismatch.into());

        let instruction = mk_ixn(
            &move_source,
            &move_dest,
            &throwaway.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&throwaway])
            .await
            .unwrap_err();
        assert_eq!(e, ProgramError::MissingRequiredSignature);
    }

    // dest lockup
    {
        let move_dest_keypair = Keypair::new();
        move_dest_type
            .new_stake_account_fully_specified(
                &mut context,
                &accounts.vote_account.pubkey(),
                minimum_delegation,
                &move_dest_keypair,
                &staker_keypair,
                &withdrawer_keypair,
                &in_force_lockup,
            )
            .await;
        let move_dest = move_dest_keypair.pubkey();

        let instruction = mk_ixn(
            &move_source,
            &move_dest,
            &staker_keypair.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, StakeError::MergeMismatch.into());
    }

    // lastly we test different vote accounts for move_stake
    if !move_lamports && move_dest_type == StakeLifecycle::Active {
        let dest_vote_account_keypair = Keypair::new();
        create_vote(
            &mut context,
            &Keypair::new(),
            &Pubkey::new_unique(),
            &Pubkey::new_unique(),
            &dest_vote_account_keypair,
        )
        .await;

        let move_dest_keypair = Keypair::new();
        move_dest_type
            .new_stake_account_fully_specified(
                &mut context,
                &dest_vote_account_keypair.pubkey(),
                minimum_delegation,
                &move_dest_keypair,
                &staker_keypair,
                &withdrawer_keypair,
                &Lockup::default(),
            )
            .await;
        let move_dest = move_dest_keypair.pubkey();

        let instruction = mk_ixn(
            &move_source,
            &move_dest,
            &staker_keypair.pubkey(),
            minimum_delegation,
        );
        let e = process_instruction(&mut context, &instruction, &vec![&staker_keypair])
            .await
            .unwrap_err();
        assert_eq!(e, StakeError::VoteAddressMismatch.into());
    }
}