casper-execution-engine 0.6.3

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

use std::{
    cell::RefCell,
    collections::{BTreeMap, BTreeSet},
    convert::TryFrom,
    iter::FromIterator,
    rc::Rc,
};

use num_rational::Ratio;
use num_traits::Zero;
use once_cell::sync::Lazy;
use parity_wasm::elements::Module;
use tracing::{debug, error, warn};

use casper_types::{
    account::AccountHash,
    auction::{
        EraValidators, ARG_AUCTION_DELAY, ARG_GENESIS_VALIDATORS, ARG_LOCKED_FUNDS_PERIOD,
        ARG_MINT_CONTRACT_PACKAGE_HASH, ARG_REWARD_FACTORS, ARG_UNBONDING_DELAY,
        ARG_VALIDATOR_PUBLIC_KEYS, ARG_VALIDATOR_SLOTS, AUCTION_DELAY_KEY, LOCKED_FUNDS_PERIOD_KEY,
        UNBONDING_DELAY_KEY, VALIDATOR_SLOTS_KEY,
    },
    bytesrepr::{self, ToBytes},
    contracts::{NamedKeys, ENTRY_POINT_NAME_INSTALL, UPGRADE_ENTRY_POINT_NAME},
    mint::{self, ARG_ROUND_SEIGNIORAGE_RATE, ROUND_SEIGNIORAGE_RATE_KEY},
    proof_of_stake, runtime_args,
    system_contract_errors::{self, mint::Error as MintError},
    AccessRights, ApiError, BlockTime, CLValue, Contract, ContractHash, ContractPackage,
    ContractPackageHash, ContractVersionKey, DeployHash, DeployInfo, EntryPoint, EntryPointType,
    Key, Phase, ProtocolVersion, RuntimeArgs, URef, U512,
};

pub use self::{
    balance::{BalanceRequest, BalanceResult},
    deploy_item::DeployItem,
    engine_config::EngineConfig,
    era_validators::{GetEraValidatorsError, GetEraValidatorsRequest},
    error::{Error, RootNotFound},
    executable_deploy_item::ExecutableDeployItem,
    execute_request::ExecuteRequest,
    execution::Error as ExecError,
    execution_result::{ExecutionResult, ExecutionResults, ForcedTransferResult},
    genesis::{ExecConfig, GenesisAccount, GenesisResult, POS_PAYMENT_PURSE},
    query::{QueryRequest, QueryResult},
    system_contract_cache::SystemContractCache,
    transfer::{TransferArgs, TransferRuntimeArgsBuilder, TransferTargetMode},
    upgrade::{UpgradeConfig, UpgradeResult},
};
use crate::{
    core::{
        engine_state::{
            execution_result::ExecutionResultBuilder,
            step::{StepRequest, StepResult},
        },
        execution::{
            self, AddressGenerator, AddressGeneratorBuilder, DirectSystemContractCall, Executor,
        },
        tracking_copy::{TrackingCopy, TrackingCopyExt},
    },
    shared::{
        account::Account,
        additive_map::AdditiveMap,
        gas::Gas,
        motes::Motes,
        newtypes::{Blake2bHash, CorrelationId},
        stored_value::StoredValue,
        transform::Transform,
        wasm_prep::{self, Preprocessor},
    },
    storage::{
        global_state::{CommitResult, StateProvider},
        protocol_data::ProtocolData,
    },
};

/// Rate for motes/gas conversion.
///
/// gas * CONV_RATE = motes
/// motes / CONV_RATE = gas
pub const CONV_RATE: u64 = 1;

pub static MAX_PAYMENT: Lazy<U512> = Lazy::new(|| U512::from(2_500_000_000 * CONV_RATE));

pub const SYSTEM_ACCOUNT_ADDR: AccountHash = AccountHash::new([0u8; 32]);

const GENESIS_INITIAL_BLOCKTIME: u64 = 0;

#[derive(Debug)]
pub struct EngineState<S> {
    config: EngineConfig,
    system_contract_cache: SystemContractCache,
    state: S,
}

#[derive(Clone, Debug)]
pub enum GetModuleResult {
    Session {
        module: Module,
        contract_package: ContractPackage,
        entry_point: EntryPoint,
    },
    Contract {
        // Contract hash
        base_key: Key,
        module: Module,
        contract: Contract,
        contract_package: ContractPackage,
        entry_point: EntryPoint,
    },
}

impl GetModuleResult {
    pub fn take_module(self) -> Module {
        match self {
            GetModuleResult::Session { module, .. } => module,
            GetModuleResult::Contract { module, .. } => module,
        }
    }
}

impl<S> EngineState<S>
where
    S: StateProvider,
    S::Error: Into<execution::Error>,
{
    pub fn new(state: S, config: EngineConfig) -> EngineState<S> {
        let system_contract_cache = Default::default();
        EngineState {
            config,
            system_contract_cache,
            state,
        }
    }

    pub fn config(&self) -> &EngineConfig {
        &self.config
    }

    pub fn get_protocol_data(
        &self,
        protocol_version: ProtocolVersion,
    ) -> Result<Option<ProtocolData>, Error> {
        match self.state.get_protocol_data(protocol_version) {
            Ok(Some(protocol_data)) => Ok(Some(protocol_data)),
            Err(error) => Err(Error::Exec(error.into())),
            _ => Ok(None),
        }
    }

    pub fn commit_genesis(
        &self,
        correlation_id: CorrelationId,
        genesis_config_hash: Blake2bHash,
        protocol_version: ProtocolVersion,
        ee_config: &ExecConfig,
    ) -> Result<GenesisResult, Error> {
        // Preliminaries
        let executor = Executor::new(self.config);
        let blocktime = BlockTime::new(GENESIS_INITIAL_BLOCKTIME);
        let gas_limit = Gas::new(std::u64::MAX.into());
        let phase = Phase::System;

        let initial_root_hash = self.state.empty_root();
        let wasm_config = ee_config.wasm_config();
        let wasmless_transfer_cost = ee_config.wasmless_transfer_cost();

        let preprocessor = Preprocessor::new(*wasm_config);

        // Spec #3: Create "virtual system account" object.
        let mut virtual_system_account = {
            let named_keys = NamedKeys::new();
            let purse = URef::new(Default::default(), AccessRights::READ_ADD_WRITE);
            Account::create(SYSTEM_ACCOUNT_ADDR, named_keys, purse)
        };

        // Spec #4: Create a runtime.
        let tracking_copy = match self.tracking_copy(initial_root_hash) {
            Ok(Some(tracking_copy)) => Rc::new(RefCell::new(tracking_copy)),
            // NOTE: As genesis is ran once per instance condition below is considered programming
            // error
            Ok(None) => panic!("state has not been initialized properly"),
            Err(error) => return Err(error),
        };

        // Persist the "virtual system account".  It will get overwritten with the actual system
        // account below.
        let key = Key::Account(SYSTEM_ACCOUNT_ADDR);
        let value = {
            let virtual_system_account = virtual_system_account.clone();
            StoredValue::Account(virtual_system_account)
        };

        tracking_copy.borrow_mut().write(key, value);

        // Spec #4A: random number generator is seeded from the hash of GenesisConfig.name
        // Updated: random number generator is seeded from genesis_config_hash from the RunGenesis
        // RPC call

        let hash_address_generator = {
            let generator = AddressGenerator::new(genesis_config_hash.as_ref(), phase);
            Rc::new(RefCell::new(generator))
        };
        let uref_address_generator = {
            let generator = AddressGenerator::new(genesis_config_hash.as_ref(), phase);
            Rc::new(RefCell::new(generator))
        };
        let transfer_address_generator = {
            let generator = AddressGenerator::new(genesis_config_hash.as_ref(), phase);
            Rc::new(RefCell::new(generator))
        };

        // Spec #6: Compute initially bonded validators as the contents of accounts_path
        // filtered to non-zero staked amounts.
        let bonded_validators: BTreeMap<AccountHash, U512> = ee_config
            .get_bonded_validators()
            .map(|genesis_account| {
                (
                    genesis_account.account_hash(),
                    genesis_account.bonded_amount().value(),
                )
            })
            .collect();

        // Spec #5: Execute the wasm code from the mint installer bytes
        let (mint_package_hash, mint_hash): (ContractPackageHash, ContractHash) = {
            let mint_installer_bytes = ee_config.mint_installer_bytes();
            let mint_installer_module = preprocessor.preprocess(mint_installer_bytes)?;

            let arg_round_seigniorage_rate: Ratio<U512> = {
                let (round_seigniorage_rate_numer, round_seigniorage_rate_denom) =
                    ee_config.round_seigniorage_rate().into();
                Ratio::new(
                    round_seigniorage_rate_numer.into(),
                    round_seigniorage_rate_denom.into(),
                )
            };

            let args = runtime_args! {
                ARG_ROUND_SEIGNIORAGE_RATE => arg_round_seigniorage_rate,
            };
            let authorization_keys: BTreeSet<AccountHash> = BTreeSet::new();
            let install_deploy_hash = DeployHash::new(genesis_config_hash.value());
            let hash_address_generator = Rc::clone(&hash_address_generator);
            let uref_address_generator = Rc::clone(&uref_address_generator);
            let transfer_address_generator = Rc::clone(&transfer_address_generator);
            let tracking_copy = Rc::clone(&tracking_copy);
            let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);
            let protocol_data = ProtocolData::default();

            executor.exec_wasm_direct(
                mint_installer_module,
                ENTRY_POINT_NAME_INSTALL,
                args,
                &mut virtual_system_account,
                authorization_keys,
                blocktime,
                install_deploy_hash,
                gas_limit,
                hash_address_generator,
                uref_address_generator,
                transfer_address_generator,
                protocol_version,
                correlation_id,
                tracking_copy,
                phase,
                protocol_data,
                system_contract_cache,
            )?
        };

        // Spec #7: Execute pos installer wasm code, passing the initially bonded validators as an
        // argument
        let (_proof_of_stake_package_hash, proof_of_stake_hash): (
            ContractPackageHash,
            ContractHash,
        ) = {
            let tracking_copy = Rc::clone(&tracking_copy);
            let hash_address_generator = Rc::clone(&hash_address_generator);
            let uref_address_generator = Rc::clone(&uref_address_generator);
            let transfer_address_generator = Rc::clone(&transfer_address_generator);
            let install_deploy_hash = DeployHash::new(genesis_config_hash.value());
            let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

            // Constructs a partial protocol data with already known uref to pass the validation
            // step
            let partial_protocol_data = ProtocolData::partial_with_mint(mint_hash);

            let proof_of_stake_installer_bytes = ee_config.proof_of_stake_installer_bytes();
            let proof_of_stake_installer_module =
                preprocessor.preprocess(proof_of_stake_installer_bytes)?;
            let args = runtime_args! {
                "mint_contract_package_hash" => mint_package_hash,
                "genesis_validators" => bonded_validators,
            };
            let authorization_keys: BTreeSet<AccountHash> = BTreeSet::new();

            executor.exec_wasm_direct(
                proof_of_stake_installer_module,
                ENTRY_POINT_NAME_INSTALL,
                args,
                &mut virtual_system_account,
                authorization_keys,
                blocktime,
                install_deploy_hash,
                gas_limit,
                hash_address_generator,
                uref_address_generator,
                transfer_address_generator,
                protocol_version,
                correlation_id,
                tracking_copy,
                phase,
                partial_protocol_data,
                system_contract_cache,
            )?
        };

        // Execute standard payment installer wasm code
        //
        // Note: this deviates from the implementation strategy described in the original
        // specification.
        let protocol_data = ProtocolData::partial_without_standard_payment(
            *wasm_config,
            mint_hash,
            proof_of_stake_hash,
        );

        let standard_payment_hash: ContractHash = {
            let standard_payment_installer_bytes = {
                // NOTE: Before integration node wasn't updated to pass the bytes, so we were
                // bundling it. This debug_assert can be removed once integration with genesis
                // works.
                debug_assert!(
                    !ee_config.standard_payment_installer_bytes().is_empty(),
                    "Caller is required to pass the standard_payment_installer bytes"
                );
                &ee_config.standard_payment_installer_bytes()
            };

            let standard_payment_installer_module =
                preprocessor.preprocess(standard_payment_installer_bytes)?;
            let args = RuntimeArgs::new();
            let authorization_keys = BTreeSet::new();
            let install_deploy_hash = DeployHash::new(genesis_config_hash.value());
            let hash_address_generator = Rc::clone(&hash_address_generator);
            let uref_address_generator = Rc::clone(&uref_address_generator);
            let transfer_address_generator = Rc::clone(&transfer_address_generator);
            let tracking_copy = Rc::clone(&tracking_copy);
            let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

            executor.exec_wasm_direct(
                standard_payment_installer_module,
                ENTRY_POINT_NAME_INSTALL,
                args,
                &mut virtual_system_account,
                authorization_keys,
                blocktime,
                install_deploy_hash,
                gas_limit,
                hash_address_generator,
                uref_address_generator,
                transfer_address_generator,
                protocol_version,
                correlation_id,
                tracking_copy,
                phase,
                protocol_data,
                system_contract_cache,
            )?
        };

        let auction_hash: ContractHash = {
            let bonded_validators: BTreeMap<casper_types::PublicKey, U512> = ee_config
                .accounts()
                .iter()
                .filter_map(|genesis_account| {
                    if genesis_account.is_genesis_validator() {
                        // NOTE: Safe as genesis validators are expected to have public key
                        // specified.
                        Some((
                            genesis_account
                                .public_key()
                                .expect("should have public key"),
                            genesis_account.bonded_amount().value(),
                        ))
                    } else {
                        None
                    }
                })
                .collect();

            let auction_installer_bytes = {
                // NOTE: Before integration node wasn't updated to pass the bytes, so we were
                // bundling it. This debug_assert can be removed once integration with genesis
                // works.
                debug_assert!(
                    !ee_config.auction_installer_bytes().is_empty(),
                    "Caller is required to pass the auction_installer bytes"
                );
                &ee_config.auction_installer_bytes()
            };

            let validator_slots = ee_config.validator_slots();
            let auction_delay = ee_config.auction_delay();
            let locked_funds_period = ee_config.locked_funds_period();
            let unbonding_delay = ee_config.unbonding_delay();
            let auction_installer_module = preprocessor.preprocess(auction_installer_bytes)?;
            let args = runtime_args! {
                ARG_MINT_CONTRACT_PACKAGE_HASH => mint_package_hash,
                ARG_GENESIS_VALIDATORS => bonded_validators,
                ARG_VALIDATOR_SLOTS => validator_slots,
                ARG_AUCTION_DELAY => auction_delay,
                ARG_LOCKED_FUNDS_PERIOD => locked_funds_period,
                ARG_UNBONDING_DELAY => unbonding_delay,
            };
            let authorization_keys = BTreeSet::new();
            let install_deploy_hash = DeployHash::new(genesis_config_hash.value());
            let hash_address_generator = Rc::clone(&hash_address_generator);
            let uref_address_generator = Rc::clone(&uref_address_generator);
            let transfer_address_generator = Rc::clone(&uref_address_generator);
            let tracking_copy = Rc::clone(&tracking_copy);
            let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

            executor.exec_wasm_direct(
                auction_installer_module,
                ENTRY_POINT_NAME_INSTALL,
                args,
                &mut virtual_system_account,
                authorization_keys,
                blocktime,
                install_deploy_hash,
                gas_limit,
                hash_address_generator,
                uref_address_generator,
                transfer_address_generator,
                protocol_version,
                correlation_id,
                tracking_copy,
                phase,
                protocol_data,
                system_contract_cache,
            )?
        };

        // Spec #2: Associate given CostTable with given ProtocolVersion.
        let protocol_data = ProtocolData::new(
            *wasm_config,
            mint_hash,
            proof_of_stake_hash,
            standard_payment_hash,
            auction_hash,
            wasmless_transfer_cost,
        );

        self.state
            .put_protocol_data(protocol_version, &protocol_data)
            .map_err(Into::into)?;

        //
        // NOTE: The following stanzas deviate from the implementation strategy described in the
        // original specification.
        //
        // It has the following benefits over that approach:
        // * It does not make an intermediate commit
        // * The system account never holds funds
        // * Similarly, the system account does not need to be handled differently than a normal
        //   account (with the exception of its known keys)
        //
        // Create known keys for chainspec accounts
        let account_named_keys = NamedKeys::new();

        // Create accounts
        {
            // Collect chainspec accounts and their known keys with the genesis account and its
            // known keys
            let accounts = {
                let mut ret: Vec<(GenesisAccount, NamedKeys)> = ee_config
                    .accounts()
                    .to_vec()
                    .into_iter()
                    .map(|account| (account, account_named_keys.clone()))
                    .collect();
                let system_account = GenesisAccount::system(Motes::zero(), Motes::zero());
                ret.push((system_account, virtual_system_account.named_keys().clone()));
                ret
            };

            // Get the mint module
            let module = {
                let contract = tracking_copy
                    .borrow_mut()
                    .get_contract(correlation_id, mint_hash)?;

                let contract_wasm = tracking_copy
                    .borrow_mut()
                    .get_contract_wasm(correlation_id, contract.contract_wasm_hash())?;
                let bytes = contract_wasm.bytes();
                wasm_prep::deserialize(&bytes)?
            };
            // For each account...
            for (account, named_keys) in accounts.into_iter() {
                let module = module.clone();
                let args = runtime_args! {
                    mint::ARG_AMOUNT => account.balance().value(),
                };
                let tracking_copy_exec = Rc::clone(&tracking_copy);
                let tracking_copy_write = Rc::clone(&tracking_copy);
                let mut named_keys_exec = NamedKeys::new();
                let base_key = mint_hash;
                let authorization_keys: BTreeSet<AccountHash> = BTreeSet::new();
                let account_hash = account.account_hash();
                let purse_creation_deploy_hash = DeployHash::new(account_hash.value());
                let hash_address_generator = Rc::clone(&hash_address_generator);
                let uref_address_generator = {
                    let generator = AddressGeneratorBuilder::new()
                        .seed_with(genesis_config_hash.as_ref())
                        .seed_with(&account_hash.to_bytes()?)
                        .seed_with(&[phase as u8])
                        .build();
                    Rc::new(RefCell::new(generator))
                };
                let transfer_address_generator = Rc::clone(&transfer_address_generator);
                let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

                let mint_result: Result<URef, MintError> = {
                    // ...call the Mint's "mint" endpoint to create purse with tokens...
                    let (_instance, mut runtime) = executor.create_runtime(
                        module,
                        EntryPointType::Contract,
                        args.clone(),
                        &mut named_keys_exec,
                        Default::default(),
                        base_key.into(),
                        &virtual_system_account,
                        authorization_keys,
                        blocktime,
                        purse_creation_deploy_hash,
                        gas_limit,
                        hash_address_generator,
                        uref_address_generator,
                        transfer_address_generator,
                        protocol_version,
                        correlation_id,
                        tracking_copy_exec,
                        phase,
                        protocol_data,
                        system_contract_cache,
                    )?;

                    runtime
                        .call_versioned_contract(
                            mint_package_hash,
                            Some(1),
                            "mint".to_string(),
                            args,
                        )?
                        .into_t::<Result<URef, MintError>>()
                        .expect("should convert")
                };

                // ...and write that account to global state...
                let key = Key::Account(account_hash);
                let value = {
                    let main_purse = mint_result?;
                    StoredValue::Account(Account::create(account_hash, named_keys, main_purse))
                };

                tracking_copy_write.borrow_mut().write(key, value);
            }
        }
        // Spec #15: Commit the transforms.
        let effects = tracking_copy.borrow().effect();

        let commit_result = self
            .state
            .commit(
                correlation_id,
                initial_root_hash,
                effects.transforms.to_owned(),
            )
            .map_err(Into::into)?;

        // Return the result
        let genesis_result = GenesisResult::from_commit_result(commit_result, effects);

        Ok(genesis_result)
    }

    pub fn commit_upgrade(
        &self,
        correlation_id: CorrelationId,
        upgrade_config: UpgradeConfig,
    ) -> Result<UpgradeResult, Error> {
        // per specification:
        // https://casperlabs.atlassian.net/wiki/spaces/EN/pages/139854367/Upgrading+System+Contracts+Specification

        // 3.1.1.1.1.1 validate pre state hash exists
        // 3.1.2.1 get a tracking_copy at the provided pre_state_hash
        let pre_state_hash = upgrade_config.pre_state_hash();
        let tracking_copy = match self.tracking_copy(pre_state_hash)? {
            Some(tracking_copy) => Rc::new(RefCell::new(tracking_copy)),
            None => return Ok(UpgradeResult::RootNotFound),
        };

        // 3.1.1.1.1.2 current protocol version is required
        let current_protocol_version = upgrade_config.current_protocol_version();
        let current_protocol_data = match self.state.get_protocol_data(current_protocol_version) {
            Ok(Some(protocol_data)) => protocol_data,
            Ok(None) => {
                return Err(Error::InvalidProtocolVersion(current_protocol_version));
            }
            Err(error) => {
                return Err(Error::Exec(error.into()));
            }
        };

        // 3.1.1.1.1.3 activation point is not currently used by EE; skipping
        // 3.1.1.1.1.4 upgrade point protocol version validation
        let new_protocol_version = upgrade_config.new_protocol_version();

        let upgrade_check_result =
            current_protocol_version.check_next_version(&new_protocol_version);

        if upgrade_check_result.is_invalid() {
            return Err(Error::InvalidProtocolVersion(new_protocol_version));
        }

        // 3.1.1.1.1.6 resolve wasm CostTable for new protocol version
        let new_wasm_config = match upgrade_config.wasm_config() {
            Some(new_wasm_costs) => new_wasm_costs,
            None => current_protocol_data.wasm_config(),
        };

        let new_wasmless_transfer_cost = match upgrade_config.new_wasmless_transfer_cost() {
            Some(new_wasmless_transfer_cost) => new_wasmless_transfer_cost,
            None => current_protocol_data.wasmless_transfer_cost(),
        };

        // 3.1.2.2 persist wasm CostTable
        let mut new_protocol_data = ProtocolData::new(
            *new_wasm_config,
            current_protocol_data.mint(),
            current_protocol_data.proof_of_stake(),
            current_protocol_data.standard_payment(),
            current_protocol_data.auction(),
            new_wasmless_transfer_cost,
        );

        self.state
            .put_protocol_data(new_protocol_version, &new_protocol_data)
            .map_err(Into::into)?;

        // 3.1.1.1.1.5 upgrade installer is optional except on major version upgrades
        match upgrade_config.upgrade_installer_bytes() {
            None if upgrade_check_result.is_code_required() => {
                // 3.1.1.1.1.5 code is required for major version bump
                return Err(Error::InvalidUpgradeConfig);
            }
            None => {
                // optional for patch/minor bumps
            }
            Some(bytes) => {
                // 3.1.2.3 execute upgrade installer if one is provided

                // preprocess installer module
                let upgrade_installer_module = {
                    let preprocessor = Preprocessor::new(*new_wasm_config);
                    preprocessor.preprocess(bytes)?
                };

                // currently there are no expected args for an upgrade installer but args are
                // supported
                let args = match upgrade_config.upgrade_installer_args() {
                    Some(args) => {
                        bytesrepr::deserialize(args.to_vec()).expect("should deserialize")
                    }
                    None => RuntimeArgs::new(),
                };

                // execute as system account
                let mut system_account = {
                    let key = Key::Account(SYSTEM_ACCOUNT_ADDR);
                    match tracking_copy.borrow_mut().read(correlation_id, &key) {
                        Ok(Some(StoredValue::Account(account))) => account,
                        Ok(_) => panic!("system account must exist"),
                        Err(error) => return Err(Error::Exec(error.into())),
                    }
                };

                let authorization_keys = {
                    let mut ret = BTreeSet::new();
                    ret.insert(SYSTEM_ACCOUNT_ADDR);
                    ret
                };

                let blocktime = BlockTime::default();

                let deploy_hash = {
                    // seeds address generator w/ protocol version
                    let bytes: Vec<u8> = upgrade_config
                        .new_protocol_version()
                        .value()
                        .into_bytes()?
                        .to_vec();
                    DeployHash::new(Blake2bHash::new(&bytes).value())
                };

                // upgrade has no gas limit; approximating with MAX
                let gas_limit = Gas::new(std::u64::MAX.into());
                let phase = Phase::System;
                let hash_address_generator = {
                    let generator = AddressGenerator::new(pre_state_hash.as_ref(), phase);
                    Rc::new(RefCell::new(generator))
                };
                let uref_address_generator = {
                    let generator = AddressGenerator::new(pre_state_hash.as_ref(), phase);
                    Rc::new(RefCell::new(generator))
                };
                let transfer_address_generator = {
                    let generator = AddressGenerator::new(pre_state_hash.as_ref(), phase);
                    Rc::new(RefCell::new(generator))
                };
                let tracking_copy = Rc::clone(&tracking_copy);
                let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

                let executor = Executor::new(self.config);

                let result: BTreeMap<ContractHash, ContractHash> = executor.exec_wasm_direct(
                    upgrade_installer_module,
                    UPGRADE_ENTRY_POINT_NAME,
                    args,
                    &mut system_account,
                    authorization_keys,
                    blocktime,
                    deploy_hash,
                    gas_limit,
                    hash_address_generator,
                    uref_address_generator,
                    transfer_address_generator,
                    new_protocol_version,
                    correlation_id,
                    Rc::clone(&tracking_copy),
                    phase,
                    new_protocol_data,
                    system_contract_cache,
                )?;

                if !new_protocol_data.update_from(result) {
                    return Err(Error::InvalidUpgradeResult);
                } else {
                    self.state
                        .put_protocol_data(new_protocol_version, &new_protocol_data)
                        .map_err(Into::into)?;
                }
            }
        }

        // 3.1.1.1.1.7 new total validator slots is optional
        if let Some(new_validator_slots) = upgrade_config.new_validator_slots() {
            // 3.1.2.4 if new total validator slots is provided, update auction contract state
            let auction_contract = tracking_copy
                .borrow_mut()
                .get_contract(correlation_id, new_protocol_data.auction())?;

            let validator_slots_key = auction_contract.named_keys()[VALIDATOR_SLOTS_KEY];
            let value = StoredValue::CLValue(
                CLValue::from_t(new_validator_slots)
                    .map_err(|_| Error::Bytesrepr("new_validator_slots".to_string()))?,
            );
            tracking_copy.borrow_mut().write(validator_slots_key, value);
        }

        if let Some(new_auction_delay) = upgrade_config.new_auction_delay() {
            let auction_contract = tracking_copy
                .borrow_mut()
                .get_contract(correlation_id, new_protocol_data.auction())?;

            let auction_delay_key = auction_contract.named_keys()[AUCTION_DELAY_KEY];
            let value = StoredValue::CLValue(
                CLValue::from_t(new_auction_delay)
                    .map_err(|_| Error::Bytesrepr("new_auction_delay".to_string()))?,
            );
            tracking_copy.borrow_mut().write(auction_delay_key, value);
        }

        if let Some(new_locked_funds_period) = upgrade_config.new_locked_funds_period() {
            let auction_contract = tracking_copy
                .borrow_mut()
                .get_contract(correlation_id, new_protocol_data.auction())?;

            let locked_funds_period_key = auction_contract.named_keys()[LOCKED_FUNDS_PERIOD_KEY];
            let value = StoredValue::CLValue(
                CLValue::from_t(new_locked_funds_period)
                    .map_err(|_| Error::Bytesrepr("new_locked_funds_period".to_string()))?,
            );
            tracking_copy
                .borrow_mut()
                .write(locked_funds_period_key, value);
        }

        if let Some(new_unbonding_delay) = upgrade_config.new_unbonding_delay() {
            let auction_contract = tracking_copy
                .borrow_mut()
                .get_contract(correlation_id, new_protocol_data.auction())?;

            let unbonding_delay_key = auction_contract.named_keys()[UNBONDING_DELAY_KEY];
            let value = StoredValue::CLValue(
                CLValue::from_t(new_unbonding_delay)
                    .map_err(|_| Error::Bytesrepr("new_unbonding_delay".to_string()))?,
            );
            tracking_copy.borrow_mut().write(unbonding_delay_key, value);
        }

        if let Some(new_round_seigniorage_rate) = upgrade_config.new_round_seigniorage_rate() {
            let new_round_seigniorage_rate: Ratio<U512> = {
                let (numer, denom) = new_round_seigniorage_rate.into();
                Ratio::new(numer.into(), denom.into())
            };

            let mint_contract = tracking_copy
                .borrow_mut()
                .get_contract(correlation_id, new_protocol_data.mint())?;

            let locked_funds_period_key = mint_contract.named_keys()[ROUND_SEIGNIORAGE_RATE_KEY];
            let value = StoredValue::CLValue(
                CLValue::from_t(new_round_seigniorage_rate)
                    .map_err(|_| Error::Bytesrepr("new_round_seigniorage_rate".to_string()))?,
            );
            tracking_copy
                .borrow_mut()
                .write(locked_funds_period_key, value);
        }

        let effects = tracking_copy.borrow().effect();

        // commit
        let commit_result = self
            .state
            .commit(
                correlation_id,
                pre_state_hash,
                effects.transforms.to_owned(),
            )
            .map_err(Into::into)?;

        // return result and effects
        Ok(UpgradeResult::from_commit_result(commit_result, effects))
    }

    pub fn tracking_copy(
        &self,
        hash: Blake2bHash,
    ) -> Result<Option<TrackingCopy<S::Reader>>, Error> {
        match self.state.checkout(hash).map_err(Into::into)? {
            Some(tc) => Ok(Some(TrackingCopy::new(tc))),
            None => Ok(None),
        }
    }

    pub fn run_query(
        &self,
        correlation_id: CorrelationId,
        query_request: QueryRequest,
    ) -> Result<QueryResult, Error> {
        let tracking_copy = match self.tracking_copy(query_request.state_hash())? {
            Some(tracking_copy) => Rc::new(RefCell::new(tracking_copy)),
            None => return Ok(QueryResult::RootNotFound),
        };

        let tracking_copy = tracking_copy.borrow();

        Ok(tracking_copy
            .query(correlation_id, query_request.key(), query_request.path())
            .map_err(|err| Error::Exec(err.into()))?
            .into())
    }

    pub fn run_execute(
        &self,
        correlation_id: CorrelationId,
        mut exec_request: ExecuteRequest,
    ) -> Result<ExecutionResults, RootNotFound> {
        let executor = Executor::new(self.config);

        let deploys = exec_request.take_deploys();
        let mut results = ExecutionResults::with_capacity(deploys.len());

        for deploy_item in deploys {
            let result = match deploy_item {
                Err(exec_result) => Ok(exec_result),
                Ok(deploy_item) => match deploy_item.session {
                    ExecutableDeployItem::Transfer { .. } => self.transfer(
                        correlation_id,
                        &executor,
                        exec_request.protocol_version,
                        exec_request.parent_state_hash,
                        BlockTime::new(exec_request.block_time),
                        deploy_item,
                        exec_request.proposer,
                    ),
                    _ => self.deploy(
                        correlation_id,
                        &executor,
                        exec_request.protocol_version,
                        exec_request.parent_state_hash,
                        BlockTime::new(exec_request.block_time),
                        deploy_item,
                        exec_request.proposer,
                    ),
                },
            };
            match result {
                Ok(result) => results.push_back(result),
                Err(error) => {
                    return Err(error);
                }
            };
        }

        Ok(results)
    }

    pub fn get_module(
        &self,
        tracking_copy: Rc<RefCell<TrackingCopy<<S as StateProvider>::Reader>>>,
        deploy_item: &ExecutableDeployItem,
        account: &Account,
        correlation_id: CorrelationId,
        preprocessor: &Preprocessor,
        protocol_version: &ProtocolVersion,
    ) -> Result<GetModuleResult, Error> {
        let (contract_package, contract, base_key) = match deploy_item {
            ExecutableDeployItem::ModuleBytes { module_bytes, .. } => {
                let module = preprocessor.preprocess(&module_bytes.as_ref())?;
                return Ok(GetModuleResult::Session {
                    module,
                    contract_package: ContractPackage::default(),
                    entry_point: EntryPoint::default(),
                });
            }
            ExecutableDeployItem::StoredContractByHash { .. }
            | ExecutableDeployItem::StoredContractByName { .. } => {
                // NOTE: `to_contract_hash_key` ensures it returns valid value only for
                // ByHash/ByName variants
                let stored_contract_key = deploy_item.to_contract_hash_key(&account)?.unwrap();

                let contract_hash = stored_contract_key
                    .into_hash()
                    .ok_or(Error::InvalidKeyVariant)?;
                let contract = tracking_copy
                    .borrow_mut()
                    .get_contract(correlation_id, contract_hash)?;

                if !contract.is_compatible_protocol_version(*protocol_version) {
                    let exec_error = execution::Error::IncompatibleProtocolMajorVersion {
                        expected: protocol_version.value().major,
                        actual: contract.protocol_version().value().major,
                    };
                    return Err(error::Error::Exec(exec_error));
                }

                let contract_package = tracking_copy
                    .borrow_mut()
                    .get_contract_package(correlation_id, contract.contract_package_hash())?;

                (contract_package, contract, stored_contract_key)
            }
            ExecutableDeployItem::StoredVersionedContractByName { version, .. }
            | ExecutableDeployItem::StoredVersionedContractByHash { version, .. } => {
                // NOTE: `to_contract_hash_key` ensures it returns valid value only for
                // ByHash/ByName variants
                let contract_package_key = deploy_item.to_contract_hash_key(&account)?.unwrap();
                let contract_package_hash = contract_package_key
                    .into_hash()
                    .ok_or(Error::InvalidKeyVariant)?;

                let contract_package = tracking_copy
                    .borrow_mut()
                    .get_contract_package(correlation_id, contract_package_hash)?;

                let maybe_version_key =
                    version.map(|ver| ContractVersionKey::new(protocol_version.value().major, ver));

                let contract_version_key = maybe_version_key
                    .or_else(|| contract_package.current_contract_version())
                    .ok_or(error::Error::Exec(
                        execution::Error::NoActiveContractVersions(contract_package_hash),
                    ))?;

                if !contract_package.is_version_enabled(contract_version_key) {
                    return Err(error::Error::Exec(
                        execution::Error::InvalidContractVersion(contract_version_key),
                    ));
                }

                let contract_hash = *contract_package
                    .lookup_contract_hash(contract_version_key)
                    .ok_or(error::Error::Exec(
                        execution::Error::InvalidContractVersion(contract_version_key),
                    ))?;

                let contract = tracking_copy
                    .borrow_mut()
                    .get_contract(correlation_id, contract_hash)?;

                (contract_package, contract, contract_package_key)
            }
            ExecutableDeployItem::Transfer { .. } => {
                return Err(error::Error::InvalidDeployItemVariant(String::from(
                    "Transfer",
                )))
            }
        };

        let entry_point_name = deploy_item.entry_point_name();

        let entry_point = contract
            .entry_point(entry_point_name)
            .cloned()
            .ok_or_else(|| {
                error::Error::Exec(execution::Error::NoSuchMethod(entry_point_name.to_owned()))
            })?;

        let contract_wasm = tracking_copy
            .borrow_mut()
            .get_contract_wasm(correlation_id, contract.contract_wasm_hash())?;

        let module = wasm_prep::deserialize(contract_wasm.bytes())?;

        match entry_point.entry_point_type() {
            EntryPointType::Session => Ok(GetModuleResult::Session {
                module,
                contract_package,
                entry_point,
            }),
            EntryPointType::Contract => Ok(GetModuleResult::Contract {
                module,
                base_key,
                contract,
                contract_package,
                entry_point,
            }),
        }
    }

    fn get_module_from_contract_hash(
        &self,
        tracking_copy: Rc<RefCell<TrackingCopy<<S as StateProvider>::Reader>>>,
        contract_hash: ContractHash,
        correlation_id: CorrelationId,
        protocol_version: &ProtocolVersion,
    ) -> Result<Module, Error> {
        let contract = tracking_copy
            .borrow_mut()
            .get_contract(correlation_id, contract_hash)?;

        // A contract may only call a stored contract that has the same protocol major version
        // number.
        if !contract.is_compatible_protocol_version(*protocol_version) {
            let exec_error = execution::Error::IncompatibleProtocolMajorVersion {
                expected: protocol_version.value().major,
                actual: contract.protocol_version().value().major,
            };
            return Err(error::Error::Exec(exec_error));
        }

        let contract_wasm = tracking_copy
            .borrow_mut()
            .get_contract_wasm(correlation_id, contract.contract_wasm_hash())?;

        let module = wasm_prep::deserialize(contract_wasm.bytes())?;

        Ok(module)
    }

    fn get_authorized_account(
        &self,
        correlation_id: CorrelationId,
        account_hash: AccountHash,
        authorization_keys: &BTreeSet<AccountHash>,
        tracking_copy: Rc<RefCell<TrackingCopy<<S as StateProvider>::Reader>>>,
    ) -> Result<Account, Error> {
        let account: Account = match tracking_copy
            .borrow_mut()
            .get_account(correlation_id, account_hash)
        {
            Ok(account) => account,
            Err(_) => {
                return Err(error::Error::Authorization);
            }
        };

        // Authorize using provided authorization keys
        if !account.can_authorize(authorization_keys) {
            return Err(error::Error::Authorization);
        }

        // Check total key weight against deploy threshold
        if !account.can_deploy_with(authorization_keys) {
            return Err(execution::Error::DeploymentAuthorizationFailure.into());
        }

        Ok(account)
    }

    pub fn get_purse_balance(
        &self,
        correlation_id: CorrelationId,
        state_hash: Blake2bHash,
        purse_uref: URef,
    ) -> Result<BalanceResult, Error> {
        let tracking_copy = match self.tracking_copy(state_hash)? {
            Some(tracking_copy) => tracking_copy,
            None => return Ok(BalanceResult::RootNotFound),
        };
        let (purse_balance_key, purse_proof) =
            tracking_copy.get_purse_balance_key_with_proof(correlation_id, purse_uref.into())?;
        let (balance, balance_proof) =
            tracking_copy.get_purse_balance_with_proof(correlation_id, purse_balance_key)?;
        let purse_proof = Box::new(purse_proof);
        let balance_proof = Box::new(balance_proof);
        let motes = balance.value();
        Ok(BalanceResult::Success {
            motes,
            purse_proof,
            balance_proof,
        })
    }

    #[allow(clippy::too_many_arguments)]
    pub fn transfer(
        &self,
        correlation_id: CorrelationId,
        executor: &Executor,
        protocol_version: ProtocolVersion,
        prestate_hash: Blake2bHash,
        blocktime: BlockTime,
        deploy_item: DeployItem,
        proposer: casper_types::PublicKey,
    ) -> Result<ExecutionResult, RootNotFound> {
        let protocol_data = match self.state.get_protocol_data(protocol_version) {
            Ok(Some(protocol_data)) => protocol_data,
            Ok(None) => {
                let error = Error::InvalidProtocolVersion(protocol_version);
                return Ok(ExecutionResult::precondition_failure(error));
            }
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(Error::Exec(
                    error.into(),
                )));
            }
        };

        let preprocessor = {
            let wasm_config = protocol_data.wasm_config();
            Preprocessor::new(*wasm_config)
        };

        let tracking_copy = match self.tracking_copy(prestate_hash) {
            Err(error) => return Ok(ExecutionResult::precondition_failure(error)),
            Ok(None) => return Err(RootNotFound::new(prestate_hash)),
            Ok(Some(tracking_copy)) => Rc::new(RefCell::new(tracking_copy)),
        };

        let base_key = Key::Account(deploy_item.address);

        let account_public_key = match base_key.into_account() {
            Some(account_addr) => account_addr,
            None => {
                return Ok(ExecutionResult::precondition_failure(
                    error::Error::Authorization,
                ));
            }
        };

        let authorization_keys = deploy_item.authorization_keys;

        let account = match self.get_authorized_account(
            correlation_id,
            account_public_key,
            &authorization_keys,
            Rc::clone(&tracking_copy),
        ) {
            Ok(account) => account,
            Err(e) => return Ok(ExecutionResult::precondition_failure(e)),
        };

        let mint_contract = match tracking_copy
            .borrow_mut()
            .get_contract(correlation_id, protocol_data.mint())
        {
            Ok(contract) => contract,
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(error.into()));
            }
        };

        let mint_module = {
            let contract_wasm_hash = mint_contract.contract_wasm_hash();
            let use_system_contracts = self.config.use_system_contracts();
            match tracking_copy.borrow_mut().get_system_module(
                correlation_id,
                contract_wasm_hash,
                use_system_contracts,
                &preprocessor,
            ) {
                Ok(module) => module,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error.into()));
                }
            }
        };

        let mut mint_named_keys = mint_contract.named_keys().to_owned();
        let mut mint_extra_keys: Vec<Key> = vec![];
        let mint_base_key = Key::from(protocol_data.mint());

        let pos_contract = match tracking_copy
            .borrow_mut()
            .get_contract(correlation_id, protocol_data.proof_of_stake())
        {
            Ok(contract) => contract,
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(error.into()));
            }
        };

        let pos_module = {
            let contract_wasm_hash = pos_contract.contract_wasm_hash();
            let use_system_contracts = self.config.use_system_contracts();
            match tracking_copy.borrow_mut().get_system_module(
                correlation_id,
                contract_wasm_hash,
                use_system_contracts,
                &preprocessor,
            ) {
                Ok(module) => module,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error.into()));
                }
            }
        };

        let mut pos_named_keys = pos_contract.named_keys().to_owned();
        let pos_extra_keys: Vec<Key> = vec![];
        let pos_base_key = Key::from(protocol_data.proof_of_stake());

        let gas_limit = Gas::new(U512::from(std::u64::MAX));

        let input_runtime_args = match deploy_item.session.into_runtime_args() {
            Ok(runtime_args) => runtime_args,
            Err(error) => return Ok(ExecutionResult::precondition_failure(error.into())),
        };

        let mut runtime_args_builder = TransferRuntimeArgsBuilder::new(input_runtime_args);
        match runtime_args_builder.transfer_target_mode(correlation_id, Rc::clone(&tracking_copy)) {
            Ok(mode) => match mode {
                TransferTargetMode::Unknown | TransferTargetMode::PurseExists(_) => { /* noop */ }
                TransferTargetMode::CreateAccount(public_key) => {
                    let (maybe_uref, execution_result): (Option<URef>, ExecutionResult) = executor
                        .exec_system_contract(
                            DirectSystemContractCall::CreatePurse,
                            mint_module.clone(),
                            RuntimeArgs::new(), // mint create takes no arguments
                            &mut mint_named_keys,
                            Default::default(),
                            mint_base_key,
                            &account,
                            authorization_keys.clone(),
                            blocktime,
                            deploy_item.deploy_hash,
                            gas_limit,
                            protocol_version,
                            correlation_id,
                            Rc::clone(&tracking_copy),
                            Phase::Session,
                            protocol_data,
                            SystemContractCache::clone(&self.system_contract_cache),
                        );
                    match maybe_uref {
                        Some(main_purse) => {
                            let new_account =
                                Account::create(public_key, Default::default(), main_purse);
                            mint_extra_keys.push(Key::from(main_purse));
                            // write new account
                            tracking_copy
                                .borrow_mut()
                                .write(Key::Account(public_key), StoredValue::Account(new_account))
                        }
                        None => {
                            return Ok(execution_result);
                        }
                    }
                }
            },
            Err(error) => {
                return Ok(ExecutionResult::Failure {
                    error,
                    effect: Default::default(),
                    transfers: Vec::default(),
                    cost: Gas::default(),
                });
            }
        }

        // Construct a payment code that will put cost of wasmless payment into payment purse
        let payment_result = {
            let transfer_args = match runtime_args_builder.clone().build(
                &account,
                correlation_id,
                Rc::clone(&tracking_copy),
            ) {
                Ok(transfer_args) => transfer_args,
                Err(error) => {
                    return Ok(ExecutionResult::Failure {
                        error,
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    });
                }
            };

            // Check source purses minimum balance

            let source_uref = transfer_args.source();

            let source_purse_balance_key = match tracking_copy
                .borrow_mut()
                .get_purse_balance_key(correlation_id, Key::URef(source_uref))
            {
                Ok(purse_balance_args) => purse_balance_args,
                Err(error) => {
                    return Ok(ExecutionResult::Failure {
                        error: Error::Exec(error),
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    });
                }
            };

            let source_purse_balance = match tracking_copy
                .borrow_mut()
                .get_purse_balance(correlation_id, source_purse_balance_key)
            {
                Ok(transfer_args) => transfer_args,
                Err(error) => {
                    return Ok(ExecutionResult::Failure {
                        error: Error::Exec(error),
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    });
                }
            };

            let wasmless_transfer_gas_cost =
                Gas::new(U512::from(protocol_data.wasmless_transfer_cost()));

            let wasmless_transfer_cost =
                Motes::from_gas(wasmless_transfer_gas_cost, CONV_RATE).expect("gas overflow");

            if source_purse_balance < wasmless_transfer_cost {
                // We can't continue if the minimum funds in source purse are lower than the
                // required cost.
                return Ok(ExecutionResult::Failure {
                    error: Error::InsufficientPayment,
                    effect: Default::default(),
                    transfers: Vec::default(),
                    cost: Gas::default(),
                });
            }

            let (payment_uref, get_payment_purse_result): (Option<URef>, ExecutionResult) =
                executor.exec_system_contract(
                    DirectSystemContractCall::GetPaymentPurse,
                    pos_module.clone(),
                    RuntimeArgs::default(),
                    &mut pos_named_keys,
                    pos_extra_keys.as_slice(),
                    pos_base_key,
                    &account,
                    authorization_keys.clone(),
                    blocktime,
                    deploy_item.deploy_hash,
                    gas_limit,
                    protocol_version,
                    correlation_id,
                    Rc::clone(&tracking_copy),
                    Phase::Payment,
                    protocol_data,
                    SystemContractCache::clone(&self.system_contract_cache),
                );

            let payment_uref = match payment_uref {
                Some(payment_uref) => payment_uref,
                None => {
                    return Ok(ExecutionResult::Failure {
                        error: Error::InsufficientPayment,
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    })
                }
            };

            if let Some(error) = get_payment_purse_result.take_error() {
                return Ok(ExecutionResult::Failure {
                    error,
                    effect: Default::default(),
                    transfers: Vec::default(),
                    cost: Gas::default(),
                });
            }

            // Create a new arguments to transfer cost of wasmless transfer into the payment purse.

            let new_transfer_args = TransferArgs::new(
                transfer_args.to(),
                transfer_args.source(),
                payment_uref,
                wasmless_transfer_gas_cost.value(),
                transfer_args.arg_id(),
            );

            let runtime_args = match RuntimeArgs::try_from(new_transfer_args) {
                Ok(runtime_args) => runtime_args,
                Err(error) => {
                    return Ok(ExecutionResult::Failure {
                        error: ExecError::from(error).into(),
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    })
                }
            };

            let (actual_result, payment_result): (Option<Result<(), u8>>, ExecutionResult) =
                executor.exec_system_contract(
                    DirectSystemContractCall::Transfer,
                    mint_module.clone(),
                    runtime_args,
                    &mut mint_named_keys,
                    mint_extra_keys.as_slice(),
                    mint_base_key,
                    &account,
                    authorization_keys.clone(),
                    blocktime,
                    deploy_item.deploy_hash,
                    gas_limit,
                    protocol_version,
                    correlation_id,
                    Rc::clone(&tracking_copy),
                    Phase::Payment,
                    protocol_data,
                    SystemContractCache::clone(&self.system_contract_cache),
                );

            if let Some(error) = payment_result.as_error().cloned() {
                return Ok(ExecutionResult::Failure {
                    error,
                    effect: Default::default(),
                    transfers: Vec::default(),
                    cost: Gas::default(),
                });
            }

            let transfer_result = match actual_result {
                Some(Ok(())) => Ok(()),
                Some(Err(mint_error)) => {
                    match system_contract_errors::mint::Error::try_from(mint_error) {
                        Ok(mint_error) => Err(ApiError::from(mint_error)),
                        Err(_) => Err(ApiError::Transfer),
                    }
                }
                None => Err(ApiError::Transfer),
            };

            if let Err(error) = transfer_result {
                return Ok(ExecutionResult::Failure {
                    error: Error::Exec(ExecError::Revert(error)),
                    effect: Default::default(),
                    transfers: Vec::default(),
                    cost: Gas::default(),
                });
            }

            let payment_purse_balance_key = match tracking_copy
                .borrow_mut()
                .get_purse_balance_key(correlation_id, Key::URef(payment_uref))
            {
                Ok(payment_purse_balance_key) => payment_purse_balance_key,
                Err(error) => {
                    return Ok(ExecutionResult::Failure {
                        error: Error::Exec(error),
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    })
                }
            };

            let payment_purse_balance = match tracking_copy
                .borrow_mut()
                .get_purse_balance(correlation_id, payment_purse_balance_key)
            {
                Ok(payment_purse_balance) => payment_purse_balance,
                Err(error) => {
                    return Ok(ExecutionResult::Failure {
                        error: Error::Exec(error),
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    })
                }
            };

            // Wasmless transfer payment code pre & post conditions:
            // (a) payment purse should be empty before the payment operation
            // (b) after executing payment code it's balance has to be equal to the wasmless gas
            // cost price
            let payment_gas =
                Gas::from_motes(payment_purse_balance, CONV_RATE).expect("gas overflow");

            debug_assert_eq!(payment_gas, wasmless_transfer_gas_cost);

            // This assumes the cost incurred is already denominated in gas

            payment_result.with_cost(payment_gas)
        };

        let transfer_args =
            match runtime_args_builder.build(&account, correlation_id, Rc::clone(&tracking_copy)) {
                Ok(runtime_args) => runtime_args,
                Err(error) => {
                    return Ok(ExecutionResult::Failure {
                        error,
                        effect: Default::default(),
                        transfers: Vec::default(),
                        cost: Gas::default(),
                    });
                }
            };

        let runtime_args = match RuntimeArgs::try_from(transfer_args) {
            Ok(runtime_args) => runtime_args,
            Err(error) => {
                return Ok(ExecutionResult::Failure {
                    error: ExecError::from(error).into(),
                    effect: Default::default(),
                    transfers: Vec::default(),
                    cost: Gas::default(),
                })
            }
        };

        let (_, mut session_result): (Option<Result<(), u8>>, ExecutionResult) = executor
            .exec_system_contract(
                DirectSystemContractCall::Transfer,
                mint_module,
                runtime_args,
                &mut mint_named_keys,
                mint_extra_keys.as_slice(),
                mint_base_key,
                &account,
                authorization_keys.clone(),
                blocktime,
                deploy_item.deploy_hash,
                gas_limit,
                protocol_version,
                correlation_id,
                Rc::clone(&tracking_copy),
                Phase::Session,
                protocol_data,
                SystemContractCache::clone(&self.system_contract_cache),
            );

        let finalize_result = {
            let proposer_purse = {
                let proposer_account: Account = match tracking_copy
                    .borrow_mut()
                    .get_account(correlation_id, AccountHash::from(&proposer))
                {
                    Ok(account) => account,
                    Err(error) => {
                        return Ok(ExecutionResult::precondition_failure(error.into()));
                    }
                };
                proposer_account.main_purse()
            };

            let proof_of_stake_args = {
                // Gas spent during payment code execution
                let finalize_cost_motes: Motes =
                    Motes::from_gas(payment_result.cost(), CONV_RATE).expect("motes overflow");

                let account = deploy_item.address;
                let maybe_runtime_args = RuntimeArgs::try_new(|args| {
                    args.insert(proof_of_stake::ARG_AMOUNT, finalize_cost_motes.value())?;
                    args.insert(proof_of_stake::ARG_ACCOUNT, account)?;
                    args.insert(proof_of_stake::ARG_TARGET, proposer_purse)?;
                    Ok(())
                });

                match maybe_runtime_args {
                    Ok(runtime_args) => runtime_args,
                    Err(error) => {
                        let exec_error = ExecError::from(error);
                        return Ok(ExecutionResult::precondition_failure(exec_error.into()));
                    }
                }
            };

            let system_account = Account::new(
                SYSTEM_ACCOUNT_ADDR,
                Default::default(),
                URef::new(Default::default(), AccessRights::READ_ADD_WRITE),
                Default::default(),
                Default::default(),
            );

            let tc = tracking_copy.borrow();
            let finalization_tc = Rc::new(RefCell::new(tc.fork()));

            let (_ret, finalize_result): (Option<()>, ExecutionResult) = executor
                .exec_system_contract(
                    DirectSystemContractCall::FinalizePayment,
                    pos_module,
                    proof_of_stake_args,
                    &mut pos_named_keys,
                    Default::default(),
                    Key::from(protocol_data.proof_of_stake()),
                    &system_account,
                    authorization_keys,
                    blocktime,
                    deploy_item.deploy_hash,
                    gas_limit,
                    protocol_version,
                    correlation_id,
                    finalization_tc,
                    Phase::FinalizePayment,
                    protocol_data,
                    SystemContractCache::clone(&self.system_contract_cache),
                );

            finalize_result
        };

        // Create + persist deploy info.
        {
            let transfers = session_result.transfers();
            let cost = payment_result.cost().value() + session_result.cost().value();
            let deploy_info = DeployInfo::new(
                deploy_item.deploy_hash,
                &transfers,
                account.account_hash(),
                account.main_purse(),
                cost,
            );
            tracking_copy.borrow_mut().write(
                Key::DeployInfo(deploy_item.deploy_hash),
                StoredValue::DeployInfo(deploy_info),
            );
        }

        if session_result.is_success() {
            session_result = session_result.with_effect(tracking_copy.borrow_mut().effect());
        }

        let mut execution_result_builder = ExecutionResultBuilder::new();
        execution_result_builder.set_payment_execution_result(payment_result);
        execution_result_builder.set_session_execution_result(session_result);
        execution_result_builder.set_finalize_execution_result(finalize_result);

        let execution_result = execution_result_builder
            .build(tracking_copy.borrow().reader(), correlation_id)
            .expect("ExecutionResultBuilder not initialized properly");

        Ok(execution_result)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn deploy(
        &self,
        correlation_id: CorrelationId,
        executor: &Executor,
        protocol_version: ProtocolVersion,
        prestate_hash: Blake2bHash,
        blocktime: BlockTime,
        deploy_item: DeployItem,
        proposer: casper_types::PublicKey,
    ) -> Result<ExecutionResult, RootNotFound> {
        // spec: https://casperlabs.atlassian.net/wiki/spaces/EN/pages/123404576/Payment+code+execution+specification

        // Obtain current protocol data for given version
        // do this first, as there is no reason to proceed if protocol version is invalid
        let protocol_data = match self.state.get_protocol_data(protocol_version) {
            Ok(Some(protocol_data)) => protocol_data,
            Ok(None) => {
                let error = Error::InvalidProtocolVersion(protocol_version);
                return Ok(ExecutionResult::precondition_failure(error));
            }
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(Error::Exec(
                    error.into(),
                )));
            }
        };

        let preprocessor = {
            let wasm_config = protocol_data.wasm_config();
            Preprocessor::new(*wasm_config)
        };

        // Create tracking copy (which functions as a deploy context)
        // validation_spec_2: prestate_hash check
        // do this second; as there is no reason to proceed if the prestate hash is invalid
        let tracking_copy = match self.tracking_copy(prestate_hash) {
            Err(error) => return Ok(ExecutionResult::precondition_failure(error)),
            Ok(None) => return Err(RootNotFound::new(prestate_hash)),
            Ok(Some(tracking_copy)) => Rc::new(RefCell::new(tracking_copy)),
        };

        let base_key = Key::Account(deploy_item.address);

        // Get addr bytes from `address` (which is actually a Key)
        // validation_spec_3: account validity
        let account_hash = match base_key.into_account() {
            Some(account_addr) => account_addr,
            None => {
                return Ok(ExecutionResult::precondition_failure(
                    error::Error::Authorization,
                ));
            }
        };

        let authorization_keys = deploy_item.authorization_keys;

        // Get account from tracking copy
        // validation_spec_3: account validity
        let account = match self.get_authorized_account(
            correlation_id,
            account_hash,
            &authorization_keys,
            Rc::clone(&tracking_copy),
        ) {
            Ok(account) => account,
            Err(e) => return Ok(ExecutionResult::precondition_failure(e)),
        };

        let session = deploy_item.session;
        let payment = deploy_item.payment;
        let deploy_hash = deploy_item.deploy_hash;

        // Create session code `A` from provided session bytes
        // validation_spec_1: valid wasm bytes
        // we do this upfront as there is no reason to continue if session logic is invalid
        let session_module = match self.get_module(
            Rc::clone(&tracking_copy),
            &session,
            &account,
            correlation_id,
            &preprocessor,
            &protocol_version,
        ) {
            Ok(module) => module,
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(error));
            }
        };

        // Get mint system contract details
        // payment_code_spec_6: system contract validity
        let mint_hash = protocol_data.mint();

        let mint_contract = match tracking_copy
            .borrow_mut()
            .get_contract(correlation_id, mint_hash)
        {
            Ok(contract) => contract,
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(error.into()));
            }
        };

        // cache mint module
        if !self.system_contract_cache.has(mint_hash) {
            let mint_module = match tracking_copy.borrow_mut().get_system_module(
                correlation_id,
                mint_contract.contract_wasm_hash(),
                self.config.use_system_contracts(),
                &preprocessor,
            ) {
                Ok(contract) => contract,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error.into()));
                }
            };

            self.system_contract_cache.insert(mint_hash, mint_module);
        }

        // Get proof of stake system contract URef from account (an account on a
        // different network may have a pos contract other than the CLPoS)
        // payment_code_spec_6: system contract validity
        let proof_of_stake_hash = protocol_data.proof_of_stake();

        // Get proof of stake system contract details
        // payment_code_spec_6: system contract validity
        let proof_of_stake_contract = match tracking_copy
            .borrow_mut()
            .get_contract(correlation_id, proof_of_stake_hash)
        {
            Ok(contract) => contract,
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(error.into()));
            }
        };

        let proof_of_stake_module = match tracking_copy.borrow_mut().get_system_module(
            correlation_id,
            proof_of_stake_contract.contract_wasm_hash(),
            self.config.use_system_contracts(),
            &preprocessor,
        ) {
            Ok(module) => module,
            Err(error) => {
                return Ok(ExecutionResult::precondition_failure(error.into()));
            }
        };

        // cache proof_of_stake module
        if !self.system_contract_cache.has(proof_of_stake_hash) {
            self.system_contract_cache
                .insert(proof_of_stake_hash, proof_of_stake_module.clone());
        }

        // Get account main purse balance key
        // validation_spec_5: account main purse minimum balance
        let account_main_purse_balance_key: Key = {
            let account_key = Key::URef(account.main_purse());
            match tracking_copy
                .borrow_mut()
                .get_purse_balance_key(correlation_id, account_key)
            {
                Ok(key) => key,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error.into()));
                }
            }
        };

        // Get account main purse balance to enforce precondition and in case of forced
        // transfer validation_spec_5: account main purse minimum balance
        let account_main_purse_balance: Motes = match tracking_copy
            .borrow_mut()
            .get_purse_balance(correlation_id, account_main_purse_balance_key)
        {
            Ok(balance) => balance,
            Err(error) => return Ok(ExecutionResult::precondition_failure(error.into())),
        };

        let max_payment_cost = Motes::new(*MAX_PAYMENT);

        // Enforce minimum main purse balance validation
        // validation_spec_5: account main purse minimum balance
        if account_main_purse_balance < max_payment_cost {
            return Ok(ExecutionResult::precondition_failure(
                Error::InsufficientPayment,
            ));
        }

        // Finalization is executed by system account (currently genesis account)
        // payment_code_spec_5: system executes finalization
        let system_account = Account::new(
            SYSTEM_ACCOUNT_ADDR,
            Default::default(),
            URef::new(Default::default(), AccessRights::READ_ADD_WRITE),
            Default::default(),
            Default::default(),
        );

        // [`ExecutionResultBuilder`] handles merging of multiple execution results
        let mut execution_result_builder = execution_result::ExecutionResultBuilder::new();

        // Execute provided payment code
        let payment_result = {
            // payment_code_spec_1: init pay environment w/ gas limit == (max_payment_cost /
            // conv_rate)
            let pay_gas_limit = Gas::from_motes(max_payment_cost, CONV_RATE).unwrap_or_default();

            let module_bytes_is_empty = match payment {
                ExecutableDeployItem::ModuleBytes {
                    ref module_bytes, ..
                } => module_bytes.is_empty(),
                _ => false,
            };

            // Create payment code module from bytes
            // validation_spec_1: valid wasm bytes
            let maybe_payment_module = if module_bytes_is_empty {
                let standard_payment_hash: ContractHash =
                    match self.state.get_protocol_data(protocol_version) {
                        Ok(Some(protocol_data)) => protocol_data.standard_payment(),
                        Ok(None) => {
                            return Ok(ExecutionResult::precondition_failure(
                                Error::InvalidProtocolVersion(protocol_version),
                            ));
                        }
                        Err(_) => return Ok(ExecutionResult::precondition_failure(Error::Deploy)),
                    };

                // if "use-system-contracts" is false, "do_nothing" wasm is returned
                self.get_module_from_contract_hash(
                    Rc::clone(&tracking_copy),
                    standard_payment_hash,
                    correlation_id,
                    &protocol_version,
                )
                .map(|module| GetModuleResult::Session {
                    module,
                    contract_package: ContractPackage::default(),
                    entry_point: EntryPoint::default(),
                })
            } else {
                self.get_module(
                    Rc::clone(&tracking_copy),
                    &payment,
                    &account,
                    correlation_id,
                    &preprocessor,
                    &protocol_version,
                )
            };

            let payment_module = match maybe_payment_module {
                Ok(module) => module,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error));
                }
            };

            // payment_code_spec_2: execute payment code
            let phase = Phase::Payment;
            let (
                payment_module,
                payment_base_key,
                mut payment_named_keys,
                payment_package,
                payment_entry_point,
            ) = match payment_module {
                GetModuleResult::Session {
                    module,
                    contract_package,
                    entry_point,
                } => (
                    module,
                    base_key,
                    account.named_keys().clone(),
                    contract_package,
                    entry_point,
                ),
                GetModuleResult::Contract {
                    module,
                    base_key,
                    contract,
                    contract_package,
                    entry_point,
                } => (
                    module,
                    base_key,
                    contract.named_keys().clone(),
                    contract_package,
                    entry_point,
                ),
            };

            let payment_args = match payment.into_runtime_args() {
                Ok(args) => args,
                Err(e) => {
                    let exec_err: execution::Error = e.into();
                    warn!("Unable to deserialize arguments: {:?}", exec_err);
                    return Ok(ExecutionResult::precondition_failure(exec_err.into()));
                }
            };

            let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

            if self.config.use_system_contracts() || !module_bytes_is_empty {
                executor.exec(
                    payment_module,
                    payment_entry_point,
                    payment_args,
                    payment_base_key,
                    &account,
                    &mut payment_named_keys,
                    authorization_keys.clone(),
                    blocktime,
                    deploy_hash,
                    pay_gas_limit,
                    protocol_version,
                    correlation_id,
                    Rc::clone(&tracking_copy),
                    phase,
                    protocol_data,
                    system_contract_cache,
                    &payment_package,
                )
            } else {
                // use host side standard payment
                let hash_address_generator = {
                    let generator = AddressGenerator::new(deploy_hash.as_bytes(), phase);
                    Rc::new(RefCell::new(generator))
                };
                let uref_address_generator = {
                    let generator = AddressGenerator::new(deploy_hash.as_bytes(), phase);
                    Rc::new(RefCell::new(generator))
                };
                let transfer_address_generator = {
                    let generator = AddressGenerator::new(deploy_hash.as_bytes(), phase);
                    Rc::new(RefCell::new(generator))
                };

                let mut runtime = match executor.create_runtime(
                    payment_module,
                    EntryPointType::Session,
                    payment_args,
                    &mut payment_named_keys,
                    Default::default(),
                    payment_base_key,
                    &account,
                    authorization_keys.clone(),
                    blocktime,
                    deploy_hash,
                    pay_gas_limit,
                    hash_address_generator,
                    uref_address_generator,
                    transfer_address_generator,
                    protocol_version,
                    correlation_id,
                    Rc::clone(&tracking_copy),
                    phase,
                    protocol_data,
                    system_contract_cache,
                ) {
                    Ok((_instance, runtime)) => runtime,
                    Err(error) => {
                        return Ok(ExecutionResult::precondition_failure(Error::Exec(error)));
                    }
                };

                let effects_snapshot = tracking_copy.borrow().effect();

                match runtime.call_host_standard_payment() {
                    Ok(()) => ExecutionResult::Success {
                        effect: runtime.context().effect(),
                        transfers: runtime.context().transfers().to_owned(),
                        cost: runtime.context().gas_counter(),
                    },
                    Err(error) => ExecutionResult::Failure {
                        error: error.into(),
                        effect: effects_snapshot,
                        transfers: runtime.context().transfers().to_owned(),
                        cost: runtime.context().gas_counter(),
                    },
                }
            }
        };

        debug!("Payment result: {:?}", payment_result);

        let payment_result_cost = payment_result.cost();
        // payment_code_spec_3: fork based upon payment purse balance and cost of
        // payment code execution
        let payment_purse_balance: Motes = {
            // Get payment purse Key from proof of stake contract
            // payment_code_spec_6: system contract validity
            let payment_purse_key: Key =
                match proof_of_stake_contract.named_keys().get(POS_PAYMENT_PURSE) {
                    Some(key) => *key,
                    None => return Ok(ExecutionResult::precondition_failure(Error::Deploy)),
                };

            let purse_balance_key = match tracking_copy
                .borrow_mut()
                .get_purse_balance_key(correlation_id, payment_purse_key)
            {
                Ok(key) => key,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error.into()));
                }
            };

            match tracking_copy
                .borrow_mut()
                .get_purse_balance(correlation_id, purse_balance_key)
            {
                Ok(balance) => balance,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error.into()));
                }
            }
        };

        // the proposer of the block this deploy is in receives the gas from this deploy execution
        let proposer_purse = {
            let proposer_account: Account = match tracking_copy
                .borrow_mut()
                .get_account(correlation_id, AccountHash::from(&proposer))
            {
                Ok(account) => account,
                Err(error) => {
                    return Ok(ExecutionResult::precondition_failure(error.into()));
                }
            };
            proposer_account.main_purse()
        };

        if let Some(forced_transfer) = payment_result.check_forced_transfer(payment_purse_balance) {
            // Get rewards purse balance key
            // payment_code_spec_6: system contract validity
            let proposer_main_purse_balance_key = {
                // Get reward purse Key from proof of stake contract
                // payment_code_spec_6: system contract validity
                match tracking_copy
                    .borrow_mut()
                    .get_purse_balance_key(correlation_id, proposer_purse.into())
                {
                    Ok(key) => key,
                    Err(error) => {
                        return Ok(ExecutionResult::precondition_failure(error.into()));
                    }
                }
            };

            let error = match forced_transfer {
                ForcedTransferResult::InsufficientPayment => Error::InsufficientPayment,
                ForcedTransferResult::PaymentFailure => payment_result
                    .take_error()
                    .unwrap_or(Error::InsufficientPayment),
            };
            match ExecutionResult::new_payment_code_error(
                error,
                max_payment_cost,
                account_main_purse_balance,
                account_main_purse_balance_key,
                proposer_main_purse_balance_key,
            ) {
                Ok(execution_result) => return Ok(execution_result),
                Err(error) => {
                    let exec_error = ExecError::from(error);
                    return Ok(ExecutionResult::precondition_failure(exec_error.into()));
                }
            }
        };

        // Transfer the contents of the rewards purse to block proposer

        execution_result_builder.set_payment_execution_result(payment_result);

        let post_payment_tracking_copy = tracking_copy.borrow();
        let session_tracking_copy = Rc::new(RefCell::new(post_payment_tracking_copy.fork()));

        // session_code_spec_2: execute session code
        let (
            session_module,
            session_base_key,
            mut session_named_keys,
            session_package,
            session_entry_point,
        ) = match session_module {
            GetModuleResult::Session {
                module,
                contract_package,
                entry_point,
            } => (
                module,
                base_key,
                account.named_keys().clone(),
                contract_package,
                entry_point,
            ),
            GetModuleResult::Contract {
                module,
                base_key,
                contract,
                contract_package,
                entry_point,
            } => (
                module,
                base_key,
                contract.named_keys().clone(),
                contract_package,
                entry_point,
            ),
        };

        let session_args = match session.into_runtime_args() {
            Ok(args) => args,
            Err(e) => {
                let exec_err: execution::Error = e.into();
                warn!("Unable to deserialize session arguments: {:?}", exec_err);
                return Ok(ExecutionResult::precondition_failure(exec_err.into()));
            }
        };
        let mut session_result = {
            // payment_code_spec_3_b_i: if (balance of PoS pay purse) >= (gas spent during
            // payment code execution) * conv_rate, yes session
            // session_code_spec_1: gas limit = ((balance of PoS payment purse) / conv_rate)
            // - (gas spent during payment execution)
            let session_gas_limit: Gas = Gas::from_motes(payment_purse_balance, CONV_RATE)
                .unwrap_or_default()
                - payment_result_cost;
            let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

            executor.exec(
                session_module,
                session_entry_point,
                session_args,
                session_base_key,
                &account,
                &mut session_named_keys,
                authorization_keys.clone(),
                blocktime,
                deploy_hash,
                session_gas_limit,
                protocol_version,
                correlation_id,
                Rc::clone(&session_tracking_copy),
                Phase::Session,
                protocol_data,
                system_contract_cache,
                &session_package,
            )
        };
        debug!("Session result: {:?}", session_result);

        // Create + persist deploy info.
        {
            let transfers = session_result.transfers();
            let cost = payment_result_cost.value() + session_result.cost().value();
            let deploy_info = DeployInfo::new(
                deploy_hash,
                &transfers,
                account.account_hash(),
                account.main_purse(),
                cost,
            );
            session_tracking_copy.borrow_mut().write(
                Key::DeployInfo(deploy_hash),
                StoredValue::DeployInfo(deploy_info),
            );
        }

        let post_session_rc = if session_result.is_failure() {
            // If session code fails we do not include its effects,
            // so we start again from the post-payment state.
            Rc::new(RefCell::new(post_payment_tracking_copy.fork()))
        } else {
            session_result = session_result.with_effect(session_tracking_copy.borrow().effect());
            session_tracking_copy
        };

        // NOTE: session_code_spec_3: (do not include session execution effects in
        // results) is enforced in execution_result_builder.build()
        execution_result_builder.set_session_execution_result(session_result);

        // payment_code_spec_5: run finalize process
        let finalize_result: ExecutionResult = {
            let post_session_tc = post_session_rc.borrow();
            let finalization_tc = Rc::new(RefCell::new(post_session_tc.fork()));

            let proof_of_stake_args = {
                //((gas spent during payment code execution) + (gas spent during session code execution)) * conv_rate
                let finalize_cost_motes: Motes =
                    Motes::from_gas(execution_result_builder.total_cost(), CONV_RATE)
                        .expect("motes overflow");

                let maybe_runtime_args = RuntimeArgs::try_new(|args| {
                    args.insert(proof_of_stake::ARG_AMOUNT, finalize_cost_motes.value())?;
                    args.insert(proof_of_stake::ARG_ACCOUNT, account_hash)?;
                    args.insert(proof_of_stake::ARG_TARGET, proposer_purse)?;
                    Ok(())
                });
                match maybe_runtime_args {
                    Ok(runtime_args) => runtime_args,
                    Err(error) => {
                        let exec_error = ExecError::from(error);
                        return Ok(ExecutionResult::precondition_failure(exec_error.into()));
                    }
                }
            };

            // The PoS keys may have changed because of effects during payment and/or
            // session, so we need to look them up again from the tracking copy
            let proof_of_stake_contract = match finalization_tc
                .borrow_mut()
                .get_contract(correlation_id, proof_of_stake_hash)
            {
                Ok(info) => info,
                Err(error) => return Ok(ExecutionResult::precondition_failure(error.into())),
            };

            let mut proof_of_stake_keys = proof_of_stake_contract.named_keys().to_owned();

            let gas_limit = Gas::new(U512::from(std::u64::MAX));
            let system_contract_cache = SystemContractCache::clone(&self.system_contract_cache);

            let (_ret, finalize_result): (Option<()>, ExecutionResult) = executor
                .exec_system_contract(
                    DirectSystemContractCall::FinalizePayment,
                    proof_of_stake_module,
                    proof_of_stake_args,
                    &mut proof_of_stake_keys,
                    Default::default(),
                    Key::from(protocol_data.proof_of_stake()),
                    &system_account,
                    authorization_keys,
                    blocktime,
                    deploy_hash,
                    gas_limit,
                    protocol_version,
                    correlation_id,
                    finalization_tc,
                    Phase::FinalizePayment,
                    protocol_data,
                    system_contract_cache,
                );

            finalize_result
        };

        execution_result_builder.set_finalize_execution_result(finalize_result);

        // We panic here to indicate that the builder was not used properly.
        let ret = execution_result_builder
            .build(tracking_copy.borrow().reader(), correlation_id)
            .expect("ExecutionResultBuilder not initialized properly");

        // NOTE: payment_code_spec_5_a is enforced in execution_result_builder.build()
        // payment_code_spec_6: return properly combined set of transforms and
        // appropriate error
        Ok(ret)
    }

    pub fn apply_effect(
        &self,
        correlation_id: CorrelationId,
        pre_state_hash: Blake2bHash,
        effects: AdditiveMap<Key, Transform>,
    ) -> Result<CommitResult, Error>
    where
        Error: From<S::Error>,
    {
        self.state
            .commit(correlation_id, pre_state_hash, effects)
            .map_err(Error::from)
    }

    /// Obtains validator weights for given era.
    pub fn get_era_validators(
        &self,
        correlation_id: CorrelationId,
        get_era_validators_request: GetEraValidatorsRequest,
    ) -> Result<EraValidators, GetEraValidatorsError> {
        let protocol_version = get_era_validators_request.protocol_version();

        let tracking_copy = match self.tracking_copy(get_era_validators_request.state_hash())? {
            Some(tracking_copy) => Rc::new(RefCell::new(tracking_copy)),
            None => return Err(GetEraValidatorsError::RootNotFound),
        };

        let protocol_data = match self.get_protocol_data(protocol_version)? {
            Some(protocol_data) => protocol_data,
            None => return Err(Error::InvalidProtocolVersion(protocol_version).into()),
        };

        let wasm_config = protocol_data.wasm_config();

        let preprocessor = Preprocessor::new(*wasm_config);

        let auction_contract: Contract = tracking_copy
            .borrow_mut()
            .get_contract(correlation_id, protocol_data.auction())
            .map_err(Error::from)?;

        let auction_module = {
            let contract_wasm_hash = auction_contract.contract_wasm_hash();
            let use_system_contracts = self.config.use_system_contracts();
            tracking_copy
                .borrow_mut()
                .get_system_module(
                    correlation_id,
                    contract_wasm_hash,
                    use_system_contracts,
                    &preprocessor,
                )
                .map_err(Error::from)?
        };

        let executor = Executor::new(self.config);

        let mut named_keys = auction_contract.named_keys().to_owned();
        let base_key = Key::from(protocol_data.auction());
        let gas_limit = Gas::new(U512::from(std::u64::MAX));
        let virtual_system_account = {
            let named_keys = NamedKeys::new();
            let purse = URef::new(Default::default(), AccessRights::READ_ADD_WRITE);
            Account::create(SYSTEM_ACCOUNT_ADDR, named_keys, purse)
        };
        let authorization_keys = BTreeSet::from_iter(vec![SYSTEM_ACCOUNT_ADDR]);
        let blocktime = BlockTime::default();
        let deploy_hash = {
            // seeds address generator w/ protocol version
            let bytes: Vec<u8> = get_era_validators_request
                .protocol_version()
                .value()
                .into_bytes()
                .map_err(Error::from)?
                .to_vec();
            DeployHash::new(Blake2bHash::new(&bytes).value())
        };

        let (era_validators, execution_result): (Option<EraValidators>, ExecutionResult) = executor
            .exec_system_contract(
                DirectSystemContractCall::GetEraValidators,
                auction_module,
                RuntimeArgs::new(),
                &mut named_keys,
                Default::default(),
                base_key,
                &virtual_system_account,
                authorization_keys,
                blocktime,
                deploy_hash,
                gas_limit,
                protocol_version,
                correlation_id,
                Rc::clone(&tracking_copy),
                Phase::Session,
                protocol_data,
                SystemContractCache::clone(&self.system_contract_cache),
            );

        if let Some(error) = execution_result.take_error() {
            return Err(error.into());
        }

        match era_validators {
            None => Err(GetEraValidatorsError::EraValidatorsMissing),
            Some(era_validators) => Ok(era_validators),
        }
    }

    pub fn commit_step(
        &self,
        correlation_id: CorrelationId,
        step_request: StepRequest,
    ) -> Result<StepResult, Error> {
        let protocol_data = match self.state.get_protocol_data(step_request.protocol_version) {
            Ok(Some(protocol_data)) => protocol_data,
            Ok(None) => {
                return Ok(StepResult::InvalidProtocolVersion);
            }
            Err(_) => {
                return Ok(StepResult::PreconditionError);
            }
        };

        let tracking_copy = match self.tracking_copy(step_request.pre_state_hash) {
            Err(_) => return Ok(StepResult::PreconditionError),
            Ok(None) => return Ok(StepResult::RootNotFound),
            Ok(Some(tracking_copy)) => Rc::new(RefCell::new(tracking_copy)),
        };

        let executor = Executor::new(self.config);

        let preprocessor = {
            let wasm_config = protocol_data.wasm_config();
            Preprocessor::new(*wasm_config)
        };

        let auction_hash = protocol_data.auction();

        let auction_contract = match tracking_copy
            .borrow_mut()
            .get_contract(correlation_id, auction_hash)
        {
            Ok(contract) => contract,
            Err(_) => {
                return Ok(StepResult::PreconditionError);
            }
        };

        let auction_module = match tracking_copy.borrow_mut().get_system_module(
            correlation_id,
            auction_contract.contract_wasm_hash(),
            self.config.use_system_contracts(),
            &preprocessor,
        ) {
            Ok(module) => module,
            Err(_) => {
                return Ok(StepResult::PreconditionError);
            }
        };

        if !self.system_contract_cache.has(auction_hash) {
            self.system_contract_cache
                .insert(auction_hash, auction_module.clone());
        }

        let virtual_system_account = {
            let named_keys = NamedKeys::new();
            let purse = URef::new(Default::default(), AccessRights::READ_ADD_WRITE);
            Account::create(SYSTEM_ACCOUNT_ADDR, named_keys, purse)
        };
        let authorization_keys = {
            let mut ret = BTreeSet::new();
            ret.insert(SYSTEM_ACCOUNT_ADDR);
            ret
        };
        let mut named_keys = auction_contract.named_keys().to_owned();
        let gas_limit = Gas::new(U512::from(std::u64::MAX));
        let deploy_hash = {
            // seeds address generator w/ protocol version
            let bytes: Vec<u8> = step_request.protocol_version.value().into_bytes()?.to_vec();
            DeployHash::new(Blake2bHash::new(&bytes).value())
        };

        let base_key = Key::from(protocol_data.auction());

        let slashed_validators = match step_request.slashed_validators() {
            Ok(slashed_validators) => slashed_validators,
            Err(error) => {
                error!(
                    "failed to deserialize validator_ids for slashing: {}",
                    error.to_string()
                );
                return Ok(StepResult::Serialization(error));
            }
        };

        let slash_args = {
            let mut runtime_args = RuntimeArgs::new();
            runtime_args
                .insert(ARG_VALIDATOR_PUBLIC_KEYS, slashed_validators)
                .map_err(|e| Error::Exec(e.into()))?;
            runtime_args
        };

        let (_, execution_result): (Option<()>, ExecutionResult) = executor.exec_system_contract(
            DirectSystemContractCall::Slash,
            auction_module.clone(),
            slash_args,
            &mut named_keys,
            Default::default(),
            base_key,
            &virtual_system_account,
            authorization_keys.clone(),
            BlockTime::default(),
            deploy_hash,
            gas_limit,
            step_request.protocol_version,
            correlation_id,
            Rc::clone(&tracking_copy),
            Phase::Session,
            protocol_data,
            SystemContractCache::clone(&self.system_contract_cache),
        );

        if let Some(exec_error) = execution_result.take_error() {
            return Ok(StepResult::SlashingError(exec_error));
        }

        let reward_factors = match step_request.reward_factors() {
            Ok(reward_factors) => reward_factors,
            Err(error) => {
                error!(
                    "failed to deserialize reward factors: {}",
                    error.to_string()
                );
                return Ok(StepResult::Serialization(error));
            }
        };

        let reward_args = {
            let maybe_runtime_args = RuntimeArgs::try_new(|args| {
                args.insert(ARG_REWARD_FACTORS, reward_factors)?;
                Ok(())
            });

            match maybe_runtime_args {
                Ok(runtime_args) => runtime_args,
                Err(error) => return Ok(StepResult::CLValueError(error)),
            }
        };

        let (_, execution_result): (Option<()>, ExecutionResult) = executor.exec_system_contract(
            DirectSystemContractCall::DistributeRewards,
            auction_module.clone(),
            reward_args,
            &mut named_keys,
            Default::default(),
            base_key,
            &virtual_system_account,
            authorization_keys.clone(),
            BlockTime::default(),
            deploy_hash,
            gas_limit,
            step_request.protocol_version,
            correlation_id,
            Rc::clone(&tracking_copy),
            Phase::Session,
            protocol_data,
            SystemContractCache::clone(&self.system_contract_cache),
        );

        if let Some(exec_error) = execution_result.take_error() {
            return Ok(StepResult::DistributeError(exec_error));
        }

        if step_request.run_auction {
            let run_auction_args = RuntimeArgs::new();

            let (_, execution_result): (Option<()>, ExecutionResult) = executor
                .exec_system_contract(
                    DirectSystemContractCall::RunAuction,
                    auction_module,
                    run_auction_args,
                    &mut named_keys,
                    Default::default(),
                    base_key,
                    &virtual_system_account,
                    authorization_keys,
                    BlockTime::default(),
                    deploy_hash,
                    gas_limit,
                    step_request.protocol_version,
                    correlation_id,
                    Rc::clone(&tracking_copy),
                    Phase::Session,
                    protocol_data,
                    SystemContractCache::clone(&self.system_contract_cache),
                );

            if let Some(exec_error) = execution_result.take_error() {
                return Ok(StepResult::AuctionError(exec_error));
            }
        }

        let effects = tracking_copy.borrow().effect();

        // commit
        let commit_result = self
            .state
            .commit(
                correlation_id,
                step_request.pre_state_hash,
                effects.transforms,
            )
            .map_err(Into::into)?;

        match commit_result {
            CommitResult::Success { state_root } => Ok(StepResult::Success {
                post_state_hash: state_root,
            }),
            CommitResult::RootNotFound => Ok(StepResult::RootNotFound),
            CommitResult::KeyNotFound(key) => Ok(StepResult::KeyNotFound(key)),
            CommitResult::TypeMismatch(type_mismatch) => {
                Ok(StepResult::TypeMismatch(type_mismatch))
            }
            CommitResult::Serialization(bytesrepr_error) => {
                Ok(StepResult::Serialization(bytesrepr_error))
            }
        }
    }
}