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

use std::{
    cmp,
    collections::{BTreeMap, BTreeSet},
    convert::TryFrom,
};

use parity_wasm::elements::Module;
use tracing::error;
use wasmi::{MemoryRef, Trap, TrapKind};

use casper_types::{
    account::{Account, AccountHash, ActionType, Weight},
    bytesrepr::{self, Bytes, FromBytes, ToBytes},
    contracts::{
        self, Contract, ContractPackage, ContractPackageStatus, ContractVersion, ContractVersions,
        DisabledVersions, EntryPoint, EntryPointAccess, EntryPoints, Group, Groups, NamedKeys,
        DEFAULT_ENTRY_POINT_NAME,
    },
    system::{
        self,
        auction::{self, Auction, EraInfo},
        handle_payment::{self, HandlePayment},
        mint::{self, Mint},
        standard_payment::{self, StandardPayment},
        CallStackElement, SystemContractType, AUCTION, HANDLE_PAYMENT, MINT, STANDARD_PAYMENT,
    },
    AccessRights, ApiError, CLTyped, CLValue, ContextAccessRights, ContractHash,
    ContractPackageHash, ContractVersionKey, ContractWasm, DeployHash, EntryPointType, EraId, Gas,
    GrantedAccess, Key, Phase, PublicKey, RuntimeArgs, StoredValue, Transfer, TransferResult,
    TransferredTo, URef, DICTIONARY_ITEM_KEY_MAX_LENGTH, U512,
};

use crate::{
    core::{
        engine_state::EngineConfig,
        execution::{self, Error},
        runtime::{host_function_flag::HostFunctionFlag, scoped_instrumenter::ScopedInstrumenter},
        runtime_context::{self, RuntimeContext},
    },
    shared::{
        host_function_costs::{Cost, HostFunction},
        wasm_prep::{self, PreprocessingError},
    },
    storage::global_state::StateReader,
};
pub use stack::{RuntimeStack, RuntimeStackFrame, RuntimeStackOverflow};

/// Represents the runtime properties of a WASM execution.
pub struct Runtime<'a, R> {
    config: EngineConfig,
    memory: Option<MemoryRef>,
    module: Option<Module>,
    host_buffer: Option<CLValue>,
    context: RuntimeContext<'a, R>,
    stack: Option<RuntimeStack>,
    host_function_flag: HostFunctionFlag,
}

impl<'a, R> Runtime<'a, R>
where
    R: StateReader<Key, StoredValue>,
    R::Error: Into<Error>,
{
    /// Creates a new runtime instance.
    pub(crate) fn new(config: EngineConfig, context: RuntimeContext<'a, R>) -> Self {
        Runtime {
            config,
            memory: None,
            module: None,
            host_buffer: None,
            context,
            stack: None,
            host_function_flag: HostFunctionFlag::default(),
        }
    }

    /// Creates a new runtime instance by cloning the config, and host function flag from `self`.
    fn new_invocation_runtime(
        &self,
        context: RuntimeContext<'a, R>,
        module: Module,
        memory: MemoryRef,
        stack: RuntimeStack,
    ) -> Self {
        Self::check_preconditions(&stack);
        Runtime {
            config: self.config,
            memory: Some(memory),
            module: Some(module),
            host_buffer: None,
            context,
            stack: Some(stack),
            host_function_flag: self.host_function_flag.clone(),
        }
    }

    /// Creates a new runtime instance with a stack from `self`.
    pub(crate) fn new_with_stack(
        &self,
        context: RuntimeContext<'a, R>,
        stack: RuntimeStack,
    ) -> Self {
        Self::check_preconditions(&stack);
        Runtime {
            config: self.config,
            memory: None,
            module: None,
            host_buffer: None,
            context,
            stack: Some(stack),
            host_function_flag: self.host_function_flag.clone(),
        }
    }

    /// Preconditions that would render the system inconsistent if violated. Those are strictly
    /// programming errors.
    fn check_preconditions(stack: &RuntimeStack) {
        if stack.is_empty() {
            error!("Call stack should not be empty while creating a new Runtime instance");
            debug_assert!(false);
        }

        if stack.first_frame().unwrap().contract_hash().is_some() {
            error!("First element of the call stack should always represent a Session call");
            debug_assert!(false);
        }
    }

    /// Returns the context.
    pub(crate) fn context(&self) -> &RuntimeContext<'a, R> {
        &self.context
    }

    fn gas(&mut self, amount: Gas) -> Result<(), Error> {
        self.context.charge_gas(amount)
    }

    /// Returns current gas counter.
    fn gas_counter(&self) -> Gas {
        self.context.gas_counter()
    }

    /// Sets new gas counter value.
    fn set_gas_counter(&mut self, new_gas_counter: Gas) {
        self.context.set_gas_counter(new_gas_counter);
    }

    /// Charge for a system contract call.
    ///
    /// This method does not charge for system contract calls if the immediate caller is a system
    /// contract or if we're currently within the scope of a host function call. This avoids
    /// misleading gas charges if one system contract calls other system contract (e.g. auction
    /// contract calls into mint to create new purses).
    pub(crate) fn charge_system_contract_call<T>(&mut self, amount: T) -> Result<(), Error>
    where
        T: Into<Gas>,
    {
        if self.host_function_flag.is_in_host_function_scope()
            || self.is_system_immediate_caller()?
        {
            // This avoids charging the user in situation when the runtime is in the middle of
            // handling a host function call or a system contract calls other system contract.
            return Ok(());
        }
        self.context.charge_system_contract_call(amount)
    }

    /// Returns bytes from the WASM memory instance.
    fn bytes_from_mem(&self, ptr: u32, size: usize) -> Result<Vec<u8>, Error> {
        self.try_get_memory()?.get(ptr, size).map_err(Into::into)
    }

    /// Returns a deserialized type from the WASM memory instance.
    fn t_from_mem<T: FromBytes>(&self, ptr: u32, size: u32) -> Result<T, Error> {
        let bytes = self.bytes_from_mem(ptr, size as usize)?;
        bytesrepr::deserialize(bytes).map_err(Into::into)
    }

    /// Reads key (defined as `key_ptr` and `key_size` tuple) from Wasm memory.
    fn key_from_mem(&mut self, key_ptr: u32, key_size: u32) -> Result<Key, Error> {
        let bytes = self.bytes_from_mem(key_ptr, key_size as usize)?;
        bytesrepr::deserialize(bytes).map_err(Into::into)
    }

    /// Reads `CLValue` (defined as `cl_value_ptr` and `cl_value_size` tuple) from Wasm memory.
    fn cl_value_from_mem(
        &mut self,
        cl_value_ptr: u32,
        cl_value_size: u32,
    ) -> Result<CLValue, Error> {
        let bytes = self.bytes_from_mem(cl_value_ptr, cl_value_size as usize)?;
        bytesrepr::deserialize(bytes).map_err(Into::into)
    }

    /// Returns a deserialized string from the WASM memory instance.
    fn string_from_mem(&self, ptr: u32, size: u32) -> Result<String, Trap> {
        let bytes = self.bytes_from_mem(ptr, size as usize)?;
        bytesrepr::deserialize(bytes).map_err(|e| Error::BytesRepr(e).into())
    }

    fn get_module_from_entry_points(
        &mut self,
        entry_points: &EntryPoints,
    ) -> Result<Vec<u8>, Error> {
        let export_section = self
            .try_get_module()?
            .export_section()
            .ok_or_else(|| Error::FunctionNotFound(String::from("Missing Export Section")))?;

        let entry_point_names: Vec<&str> = entry_points.keys().map(|s| s.as_str()).collect();

        let maybe_missing_name: Option<String> = entry_point_names
            .iter()
            .find(|name| {
                !export_section
                    .entries()
                    .iter()
                    .any(|export_entry| export_entry.field() == **name)
            })
            .map(|s| String::from(*s));

        if let Some(missing_name) = maybe_missing_name {
            Err(Error::FunctionNotFound(missing_name))
        } else {
            let mut module = self.try_get_module()?.clone();
            pwasm_utils::optimize(&mut module, entry_point_names)?;
            parity_wasm::serialize(module).map_err(Error::ParityWasm)
        }
    }

    #[allow(clippy::wrong_self_convention)]
    fn is_valid_uref(&mut self, uref_ptr: u32, uref_size: u32) -> Result<bool, Trap> {
        let bytes = self.bytes_from_mem(uref_ptr, uref_size as usize)?;
        let uref: URef = bytesrepr::deserialize(bytes).map_err(Error::BytesRepr)?;
        Ok(self.context.validate_uref(&uref).is_ok())
    }

    /// Load the uref known by the given name into the Wasm memory
    fn load_key(
        &mut self,
        name_ptr: u32,
        name_size: u32,
        output_ptr: u32,
        output_size: usize,
        bytes_written_ptr: u32,
    ) -> Result<Result<(), ApiError>, Trap> {
        let name = self.string_from_mem(name_ptr, name_size)?;

        // Get a key and serialize it
        let key = match self.context.named_keys_get(&name) {
            Some(key) => key,
            None => return Ok(Err(ApiError::MissingKey)),
        };

        let key_bytes = match key.to_bytes() {
            Ok(bytes) => bytes,
            Err(error) => return Ok(Err(error.into())),
        };

        // `output_size` has to be greater or equal to the actual length of serialized Key bytes
        if output_size < key_bytes.len() {
            return Ok(Err(ApiError::BufferTooSmall));
        }

        // Set serialized Key bytes into the output buffer
        if let Err(error) = self.try_get_memory()?.set(output_ptr, &key_bytes) {
            return Err(Error::Interpreter(error.into()).into());
        }

        // For all practical purposes following cast is assumed to be safe
        let bytes_size = key_bytes.len() as u32;
        let size_bytes = bytes_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self.try_get_memory()?.set(bytes_written_ptr, &size_bytes) {
            return Err(Error::Interpreter(error.into()).into());
        }

        Ok(Ok(()))
    }

    fn has_key(&mut self, name_ptr: u32, name_size: u32) -> Result<i32, Trap> {
        let name = self.string_from_mem(name_ptr, name_size)?;
        if self.context.named_keys_contains_key(&name) {
            Ok(0)
        } else {
            Ok(1)
        }
    }

    fn put_key(
        &mut self,
        name_ptr: u32,
        name_size: u32,
        key_ptr: u32,
        key_size: u32,
    ) -> Result<(), Trap> {
        let name = self.string_from_mem(name_ptr, name_size)?;
        let key = self.key_from_mem(key_ptr, key_size)?;
        self.context.put_key(name, key).map_err(Into::into)
    }

    fn remove_key(&mut self, name_ptr: u32, name_size: u32) -> Result<(), Trap> {
        let name = self.string_from_mem(name_ptr, name_size)?;
        self.context.remove_key(&name)?;
        Ok(())
    }

    /// Writes runtime context's account main purse to dest_ptr in the Wasm memory.
    fn get_main_purse(&mut self, dest_ptr: u32) -> Result<(), Trap> {
        let purse = self.context.get_main_purse()?;
        let purse_bytes = purse.into_bytes().map_err(Error::BytesRepr)?;
        self.try_get_memory()?
            .set(dest_ptr, &purse_bytes)
            .map_err(|e| Error::Interpreter(e.into()).into())
    }

    /// Writes caller (deploy) account public key to dest_ptr in the Wasm
    /// memory.
    fn get_caller(&mut self, output_size: u32) -> Result<Result<(), ApiError>, Trap> {
        if !self.can_write_to_host_buffer() {
            // Exit early if the host buffer is already occupied
            return Ok(Err(ApiError::HostBufferFull));
        }
        let value = CLValue::from_t(self.context.get_caller()).map_err(Error::CLValue)?;
        let value_size = value.inner_bytes().len();

        // Save serialized public key into host buffer
        if let Err(error) = self.write_host_buffer(value) {
            return Ok(Err(error));
        }

        // Write output
        let output_size_bytes = value_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self.try_get_memory()?.set(output_size, &output_size_bytes) {
            return Err(Error::Interpreter(error.into()).into());
        }
        Ok(Ok(()))
    }

    /// Gets the immediate caller of the current execution
    fn get_immediate_caller(&self) -> Option<&CallStackElement> {
        self.stack.as_ref().and_then(|stack| stack.previous_frame())
    }

    /// Checks if immediate caller is of session type of the same account as the provided account
    /// hash.
    fn is_allowed_session_caller(&self, provided_account_hash: &AccountHash) -> bool {
        if let Some(CallStackElement::Session { account_hash }) = self.get_immediate_caller() {
            return account_hash == provided_account_hash;
        }
        false
    }

    /// Writes runtime context's phase to dest_ptr in the Wasm memory.
    fn get_phase(&mut self, dest_ptr: u32) -> Result<(), Trap> {
        let phase = self.context.phase();
        let bytes = phase.into_bytes().map_err(Error::BytesRepr)?;
        self.try_get_memory()?
            .set(dest_ptr, &bytes)
            .map_err(|e| Error::Interpreter(e.into()).into())
    }

    /// Writes current blocktime to dest_ptr in Wasm memory.
    fn get_blocktime(&self, dest_ptr: u32) -> Result<(), Trap> {
        let blocktime = self
            .context
            .get_blocktime()
            .into_bytes()
            .map_err(Error::BytesRepr)?;
        self.try_get_memory()?
            .set(dest_ptr, &blocktime)
            .map_err(|e| Error::Interpreter(e.into()).into())
    }

    /// Load the uref known by the given name into the Wasm memory
    fn load_call_stack(
        &mut self,
        // (Output) Pointer to number of elements in the call stack.
        call_stack_len_ptr: u32,
        // (Output) Pointer to size in bytes of the serialized call stack.
        result_size_ptr: u32,
    ) -> Result<Result<(), ApiError>, Trap> {
        if !self.can_write_to_host_buffer() {
            // Exit early if the host buffer is already occupied
            return Ok(Err(ApiError::HostBufferFull));
        }
        let call_stack = match self.try_get_stack() {
            Ok(stack) => stack.call_stack_elements(),
            Err(_error) => return Ok(Err(ApiError::Unhandled)),
        };
        let call_stack_len = call_stack.len() as u32;
        let call_stack_len_bytes = call_stack_len.to_le_bytes();

        if let Err(error) = self
            .try_get_memory()?
            .set(call_stack_len_ptr, &call_stack_len_bytes)
        {
            return Err(Error::Interpreter(error.into()).into());
        }

        if call_stack_len == 0 {
            return Ok(Ok(()));
        }

        let call_stack_cl_value = CLValue::from_t(call_stack.clone()).map_err(Error::CLValue)?;

        let call_stack_cl_value_bytes_len = call_stack_cl_value.inner_bytes().len() as u32;
        if let Err(error) = self.write_host_buffer(call_stack_cl_value) {
            return Ok(Err(error));
        }

        let call_stack_cl_value_bytes_len_bytes = call_stack_cl_value_bytes_len.to_le_bytes();

        if let Err(error) = self
            .try_get_memory()?
            .set(result_size_ptr, &call_stack_cl_value_bytes_len_bytes)
        {
            return Err(Error::Interpreter(error.into()).into());
        }

        Ok(Ok(()))
    }

    /// Return some bytes from the memory and terminate the current `sub_call`. Note that the return
    /// type is `Trap`, indicating that this function will always kill the current Wasm instance.
    fn ret(
        &mut self,
        value_ptr: u32,
        value_size: usize,
        scoped_instrumenter: &mut ScopedInstrumenter,
    ) -> Trap {
        const UREF_COUNT: &str = "uref_count";
        self.host_buffer = None;
        let memory = match self.try_get_memory() {
            Ok(memory) => memory,
            Err(error) => return Trap::from(error),
        };
        let mem_get = memory
            .get(value_ptr, value_size)
            .map_err(|e| Error::Interpreter(e.into()));
        match mem_get {
            Ok(buf) => {
                // Set the result field in the runtime and return the proper element of the `Error`
                // enum indicating that the reason for exiting the module was a call to ret.
                self.host_buffer = bytesrepr::deserialize(buf).ok();

                let urefs = match &self.host_buffer {
                    Some(buf) => utils::extract_urefs(buf),
                    None => Ok(vec![]),
                };
                match urefs {
                    Ok(urefs) => {
                        scoped_instrumenter.add_property(UREF_COUNT, urefs.len());
                        for uref in &urefs {
                            if let Err(error) = self.context.validate_uref(uref) {
                                return Trap::from(error);
                            }
                        }
                        Error::Ret(urefs).into()
                    }
                    Err(e) => {
                        scoped_instrumenter.add_property(UREF_COUNT, 0);
                        e.into()
                    }
                }
            }
            Err(e) => {
                scoped_instrumenter.add_property(UREF_COUNT, 0);
                e.into()
            }
        }
    }

    /// Checks if a [`Key`] is a system contract.
    fn is_system_contract(&self, key: Key) -> Result<bool, Error> {
        let contract_hash = match key.into_hash() {
            Some(contract_hash_bytes) => ContractHash::new(contract_hash_bytes),
            None => return Ok(false),
        };

        self.context.is_system_contract(&contract_hash)
    }

    /// Checks if current context is the mint system contract.
    pub(crate) fn is_mint(&self, key: Key) -> bool {
        let hash = match self.context.get_system_contract(MINT) {
            Ok(hash) => hash,
            Err(_) => {
                error!("Failed to get system mint contract hash");
                return false;
            }
        };
        key.into_hash() == Some(hash.value())
    }

    /// Checks if current context is the `handle_payment` system contract.
    pub(crate) fn is_handle_payment(&self, key: Key) -> bool {
        let hash = match self.context.get_system_contract(HANDLE_PAYMENT) {
            Ok(hash) => hash,
            Err(_) => {
                error!("Failed to get system handle payment contract hash");
                return false;
            }
        };
        key.into_hash() == Some(hash.value())
    }

    /// Checks if current context is the auction system contract.
    pub(crate) fn is_auction(&self, key: Key) -> bool {
        let hash = match self.context.get_system_contract(AUCTION) {
            Ok(hash) => hash,
            Err(_) => {
                error!("Failed to get system auction contract hash");
                return false;
            }
        };
        key.into_hash() == Some(hash.value())
    }

    fn get_named_argument<T: FromBytes + CLTyped>(
        args: &RuntimeArgs,
        name: &str,
    ) -> Result<T, Error> {
        let arg: CLValue = args
            .get(name)
            .cloned()
            .ok_or(Error::Revert(ApiError::MissingArgument))?;
        arg.into_t()
            .map_err(|_| Error::Revert(ApiError::InvalidArgument))
    }

    fn reverter<T: Into<ApiError>>(error: T) -> Error {
        let api_error: ApiError = error.into();
        // NOTE: This is special casing needed to keep the native system contracts propagate
        // GasLimit properly to the user. Once support for wasm system contract will be dropped this
        // won't be necessary anymore.
        match api_error {
            ApiError::Mint(mint_error) if mint_error == mint::Error::GasLimit as u8 => {
                Error::GasLimit
            }
            ApiError::AuctionError(auction_error)
                if auction_error == auction::Error::GasLimit as u8 =>
            {
                Error::GasLimit
            }
            ApiError::HandlePayment(handle_payment_error)
                if handle_payment_error == handle_payment::Error::GasLimit as u8 =>
            {
                Error::GasLimit
            }
            api_error => Error::Revert(api_error),
        }
    }

    /// Calls host mint contract.
    fn call_host_mint(
        &mut self,
        entry_point_name: &str,
        named_keys: &mut NamedKeys,
        runtime_args: &RuntimeArgs,
        access_rights: ContextAccessRights,
        stack: RuntimeStack,
    ) -> Result<CLValue, Error> {
        let gas_counter = self.gas_counter();

        let base_key = self.context.get_system_contract(MINT)?.into();
        let runtime_context = self.context.new_from_self(
            base_key,
            EntryPointType::Contract,
            named_keys,
            access_rights,
            runtime_args.to_owned(),
        );

        let mut mint_runtime = self.new_with_stack(runtime_context, stack);

        let system_config = self.config.system_config();
        let mint_costs = system_config.mint_costs();

        let result = match entry_point_name {
            // Type: `fn mint(amount: U512) -> Result<URef, Error>`
            mint::METHOD_MINT => (|| {
                mint_runtime.charge_system_contract_call(mint_costs.mint)?;

                let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
                let result: Result<URef, mint::Error> = mint_runtime.mint(amount);
                if let Err(mint::Error::GasLimit) = result {
                    return Err(execution::Error::GasLimit);
                }
                CLValue::from_t(result).map_err(Self::reverter)
            })(),
            mint::METHOD_REDUCE_TOTAL_SUPPLY => (|| {
                mint_runtime.charge_system_contract_call(mint_costs.reduce_total_supply)?;

                let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
                let result: Result<(), mint::Error> = mint_runtime.reduce_total_supply(amount);
                CLValue::from_t(result).map_err(Self::reverter)
            })(),
            // Type: `fn create() -> URef`
            mint::METHOD_CREATE => (|| {
                mint_runtime.charge_system_contract_call(mint_costs.create)?;

                let uref = mint_runtime.mint(U512::zero()).map_err(Self::reverter)?;
                CLValue::from_t(uref).map_err(Self::reverter)
            })(),
            // Type: `fn balance(purse: URef) -> Option<U512>`
            mint::METHOD_BALANCE => (|| {
                mint_runtime.charge_system_contract_call(mint_costs.balance)?;

                let uref: URef = Self::get_named_argument(runtime_args, mint::ARG_PURSE)?;
                let maybe_balance: Option<U512> =
                    mint_runtime.balance(uref).map_err(Self::reverter)?;
                CLValue::from_t(maybe_balance).map_err(Self::reverter)
            })(),
            // Type: `fn transfer(maybe_to: Option<AccountHash>, source: URef, target: URef, amount:
            // U512, id: Option<u64>) -> Result<(), Error>`
            mint::METHOD_TRANSFER => (|| {
                mint_runtime.charge_system_contract_call(mint_costs.transfer)?;

                let maybe_to: Option<AccountHash> =
                    Self::get_named_argument(runtime_args, mint::ARG_TO)?;
                let source: URef = Self::get_named_argument(runtime_args, mint::ARG_SOURCE)?;
                let target: URef = Self::get_named_argument(runtime_args, mint::ARG_TARGET)?;
                let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
                let id: Option<u64> = Self::get_named_argument(runtime_args, mint::ARG_ID)?;
                let result: Result<(), mint::Error> =
                    mint_runtime.transfer(maybe_to, source, target, amount, id);
                CLValue::from_t(result).map_err(Self::reverter)
            })(),
            // Type: `fn read_base_round_reward() -> Result<U512, Error>`
            mint::METHOD_READ_BASE_ROUND_REWARD => (|| {
                mint_runtime.charge_system_contract_call(mint_costs.read_base_round_reward)?;

                let result: U512 = mint_runtime
                    .read_base_round_reward()
                    .map_err(Self::reverter)?;
                CLValue::from_t(result).map_err(Self::reverter)
            })(),
            mint::METHOD_MINT_INTO_EXISTING_PURSE => (|| {
                mint_runtime.charge_system_contract_call(mint_costs.mint)?;

                let amount: U512 = Self::get_named_argument(runtime_args, mint::ARG_AMOUNT)?;
                let existing_purse: URef = Self::get_named_argument(runtime_args, mint::ARG_PURSE)?;

                let result: Result<(), mint::Error> =
                    mint_runtime.mint_into_existing_purse(existing_purse, amount);
                CLValue::from_t(result).map_err(Self::reverter)
            })(),

            _ => CLValue::from_t(()).map_err(Self::reverter),
        };

        // Charge just for the amount that particular entry point cost - using gas cost from the
        // isolated runtime might have a recursive costs whenever system contract calls other system
        // contract.
        self.gas(match mint_runtime.gas_counter().checked_sub(gas_counter) {
            None => gas_counter,
            Some(new_gas) => new_gas,
        })?;

        // Result still contains a result, but the entrypoints logic does not exit early on errors.
        let ret = result?;

        // Update outer spending approved limit.
        self.context
            .set_remaining_spending_limit(mint_runtime.context.remaining_spending_limit());

        let urefs = utils::extract_urefs(&ret)?;
        self.context.access_rights_extend(&urefs);
        {
            let transfers = self.context.transfers_mut();
            *transfers = mint_runtime.context.transfers().to_owned();
        }
        Ok(ret)
    }

    /// Calls host `handle_payment` contract.
    fn call_host_handle_payment(
        &mut self,
        entry_point_name: &str,
        named_keys: &mut NamedKeys,
        runtime_args: &RuntimeArgs,
        access_rights: ContextAccessRights,
        stack: RuntimeStack,
    ) -> Result<CLValue, Error> {
        let gas_counter = self.gas_counter();

        let base_key = self.context.get_system_contract(HANDLE_PAYMENT)?.into();
        let runtime_context = self.context.new_from_self(
            base_key,
            EntryPointType::Contract,
            named_keys,
            access_rights,
            runtime_args.to_owned(),
        );

        let mut runtime = self.new_with_stack(runtime_context, stack);

        let system_config = self.config.system_config();
        let handle_payment_costs = system_config.handle_payment_costs();

        let result = match entry_point_name {
            handle_payment::METHOD_GET_PAYMENT_PURSE => (|| {
                runtime.charge_system_contract_call(handle_payment_costs.get_payment_purse)?;

                let rights_controlled_purse =
                    runtime.get_payment_purse().map_err(Self::reverter)?;
                CLValue::from_t(rights_controlled_purse).map_err(Self::reverter)
            })(),
            handle_payment::METHOD_SET_REFUND_PURSE => (|| {
                runtime.charge_system_contract_call(handle_payment_costs.set_refund_purse)?;

                let purse: URef =
                    Self::get_named_argument(runtime_args, handle_payment::ARG_PURSE)?;
                runtime.set_refund_purse(purse).map_err(Self::reverter)?;
                CLValue::from_t(()).map_err(Self::reverter)
            })(),
            handle_payment::METHOD_GET_REFUND_PURSE => (|| {
                runtime.charge_system_contract_call(handle_payment_costs.get_refund_purse)?;

                let maybe_purse = runtime.get_refund_purse().map_err(Self::reverter)?;
                CLValue::from_t(maybe_purse).map_err(Self::reverter)
            })(),
            handle_payment::METHOD_FINALIZE_PAYMENT => (|| {
                runtime.charge_system_contract_call(handle_payment_costs.finalize_payment)?;

                let amount_spent: U512 =
                    Self::get_named_argument(runtime_args, handle_payment::ARG_AMOUNT)?;
                let account: AccountHash =
                    Self::get_named_argument(runtime_args, handle_payment::ARG_ACCOUNT)?;
                let target: URef =
                    Self::get_named_argument(runtime_args, handle_payment::ARG_TARGET)?;
                runtime
                    .finalize_payment(amount_spent, account, target)
                    .map_err(Self::reverter)?;
                CLValue::from_t(()).map_err(Self::reverter)
            })(),
            _ => CLValue::from_t(()).map_err(Self::reverter),
        };

        self.gas(match runtime.gas_counter().checked_sub(gas_counter) {
            None => gas_counter,
            Some(new_gas) => new_gas,
        })?;

        let ret = result?;
        let urefs = utils::extract_urefs(&ret)?;
        self.context.access_rights_extend(&urefs);
        {
            let transfers = self.context.transfers_mut();
            *transfers = runtime.context.transfers().to_owned();
        }
        Ok(ret)
    }

    /// Calls host standard payment contract.
    pub(crate) fn call_host_standard_payment(&mut self, stack: RuntimeStack) -> Result<(), Error> {
        // NOTE: This method (unlike other call_host_* methods) already runs on its own runtime
        // context.
        self.stack = Some(stack);
        let gas_counter = self.gas_counter();
        let amount: U512 =
            Self::get_named_argument(self.context.args(), standard_payment::ARG_AMOUNT)?;
        let result = self.pay(amount).map_err(Self::reverter);
        self.set_gas_counter(gas_counter);
        result
    }

    /// Calls host auction contract.
    fn call_host_auction(
        &mut self,
        entry_point_name: &str,
        named_keys: &mut NamedKeys,
        runtime_args: &RuntimeArgs,
        access_rights: ContextAccessRights,
        stack: RuntimeStack,
    ) -> Result<CLValue, Error> {
        let gas_counter = self.gas_counter();

        let base_key = self.context.get_system_contract(AUCTION)?.into();
        let runtime_context = self.context.new_from_self(
            base_key,
            EntryPointType::Contract,
            named_keys,
            access_rights,
            runtime_args.to_owned(),
        );

        let mut runtime = self.new_with_stack(runtime_context, stack);

        let system_config = self.config.system_config();
        let auction_costs = system_config.auction_costs();

        let result = match entry_point_name {
            auction::METHOD_GET_ERA_VALIDATORS => (|| {
                runtime.charge_system_contract_call(auction_costs.get_era_validators)?;

                let result = runtime.get_era_validators().map_err(Self::reverter)?;

                CLValue::from_t(result).map_err(Self::reverter)
            })(),

            auction::METHOD_ADD_BID => (|| {
                runtime.charge_system_contract_call(auction_costs.add_bid)?;

                let account_hash = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
                let delegation_rate =
                    Self::get_named_argument(runtime_args, auction::ARG_DELEGATION_RATE)?;
                let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;

                let result = runtime
                    .add_bid(account_hash, delegation_rate, amount)
                    .map_err(Self::reverter)?;

                CLValue::from_t(result).map_err(Self::reverter)
            })(),

            auction::METHOD_WITHDRAW_BID => (|| {
                runtime.charge_system_contract_call(auction_costs.withdraw_bid)?;

                let account_hash = Self::get_named_argument(runtime_args, auction::ARG_PUBLIC_KEY)?;
                let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;

                let result = runtime
                    .withdraw_bid(account_hash, amount)
                    .map_err(Self::reverter)?;
                CLValue::from_t(result).map_err(Self::reverter)
            })(),

            auction::METHOD_DELEGATE => (|| {
                runtime.charge_system_contract_call(auction_costs.delegate)?;

                let delegator = Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR)?;
                let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
                let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;

                let max_delegator_size_limit = self.config.max_delegator_size_limit() as usize;
                let minimum_delegation_amount = self.config.minimum_delegation_amount();

                let result = runtime
                    .delegate(
                        delegator,
                        validator,
                        amount,
                        max_delegator_size_limit,
                        minimum_delegation_amount,
                    )
                    .map_err(Self::reverter)?;

                CLValue::from_t(result).map_err(Self::reverter)
            })(),

            auction::METHOD_UNDELEGATE => (|| {
                runtime.charge_system_contract_call(auction_costs.undelegate)?;

                let delegator = Self::get_named_argument(runtime_args, auction::ARG_DELEGATOR)?;
                let validator = Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR)?;
                let amount = Self::get_named_argument(runtime_args, auction::ARG_AMOUNT)?;

                let result = runtime
                    .undelegate(delegator, validator, amount)
                    .map_err(Self::reverter)?;

                CLValue::from_t(result).map_err(Self::reverter)
            })(),

            auction::METHOD_RUN_AUCTION => (|| {
                runtime.charge_system_contract_call(auction_costs.run_auction)?;

                let era_end_timestamp_millis =
                    Self::get_named_argument(runtime_args, auction::ARG_ERA_END_TIMESTAMP_MILLIS)?;
                let evicted_validators =
                    Self::get_named_argument(runtime_args, auction::ARG_EVICTED_VALIDATORS)?;

                runtime
                    .run_auction(era_end_timestamp_millis, evicted_validators)
                    .map_err(Self::reverter)?;

                CLValue::from_t(()).map_err(Self::reverter)
            })(),

            // Type: `fn slash(validator_account_hashes: &[AccountHash]) -> Result<(), Error>`
            auction::METHOD_SLASH => (|| {
                runtime.charge_system_contract_call(auction_costs.slash)?;

                let validator_public_keys =
                    Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR_PUBLIC_KEYS)?;
                runtime
                    .slash(validator_public_keys)
                    .map_err(Self::reverter)?;
                CLValue::from_t(()).map_err(Self::reverter)
            })(),

            // Type: `fn distribute(reward_factors: BTreeMap<PublicKey, u64>) -> Result<(), Error>`
            auction::METHOD_DISTRIBUTE => (|| {
                runtime.charge_system_contract_call(auction_costs.distribute)?;

                let reward_factors: BTreeMap<PublicKey, u64> =
                    Self::get_named_argument(runtime_args, auction::ARG_REWARD_FACTORS)?;
                runtime.distribute(reward_factors).map_err(Self::reverter)?;
                CLValue::from_t(()).map_err(Self::reverter)
            })(),

            // Type: `fn read_era_id() -> Result<EraId, Error>`
            auction::METHOD_READ_ERA_ID => (|| {
                runtime.charge_system_contract_call(auction_costs.read_era_id)?;

                let result = runtime.read_era_id().map_err(Self::reverter)?;
                CLValue::from_t(result).map_err(Self::reverter)
            })(),

            auction::METHOD_ACTIVATE_BID => (|| {
                runtime.charge_system_contract_call(auction_costs.read_era_id)?;

                let validator_public_key: PublicKey =
                    Self::get_named_argument(runtime_args, auction::ARG_VALIDATOR_PUBLIC_KEY)?;

                runtime
                    .activate_bid(validator_public_key)
                    .map_err(Self::reverter)?;

                CLValue::from_t(()).map_err(Self::reverter)
            })(),

            _ => CLValue::from_t(()).map_err(Self::reverter),
        };

        // Charge for the gas spent during execution in an isolated runtime.
        self.gas(match runtime.gas_counter().checked_sub(gas_counter) {
            None => gas_counter,
            Some(new_gas) => new_gas,
        })?;

        // Result still contains a result, but the entrypoints logic does not exit early on errors.
        let ret = result?;

        let urefs = utils::extract_urefs(&ret)?;
        self.context.access_rights_extend(&urefs);
        {
            let transfers = self.context.transfers_mut();
            *transfers = runtime.context.transfers().to_owned();
        }

        Ok(ret)
    }

    /// Call a contract by pushing a stack element onto the frame.
    pub(crate) fn call_contract_with_stack(
        &mut self,
        contract_hash: ContractHash,
        entry_point_name: &str,
        args: RuntimeArgs,
        stack: RuntimeStack,
    ) -> Result<CLValue, Error> {
        self.stack = Some(stack);
        self.call_contract(contract_hash, entry_point_name, args)
    }

    pub(crate) fn execute_module_bytes(
        &mut self,
        module_bytes: &Bytes,
        stack: RuntimeStack,
    ) -> Result<CLValue, Error> {
        let protocol_version = self.context.protocol_version();
        let wasm_config = self.config.wasm_config();
        let module = wasm_prep::preprocess(*wasm_config, module_bytes)?;
        let (instance, memory) =
            utils::instance_and_memory(module.clone(), protocol_version, wasm_config)?;
        self.memory = Some(memory);
        self.module = Some(module);
        self.stack = Some(stack);
        self.context.set_args(utils::attenuate_uref_in_args(
            self.context.args().clone(),
            self.context.account().main_purse().addr(),
            AccessRights::WRITE,
        )?);

        let result = instance.invoke_export(DEFAULT_ENTRY_POINT_NAME, &[], self);

        let error = match result {
            Err(error) => error,
            // If `Ok` and the `host_buffer` is `None`, the contract's execution succeeded but did
            // not explicitly call `runtime::ret()`.  Treat as though the execution
            // returned the unit type `()` as per Rust functions which don't specify a
            // return value.
            Ok(_) => {
                return Ok(self.take_host_buffer().unwrap_or(CLValue::from_t(())?));
            }
        };

        if let Some(host_error) = error.as_host_error() {
            // If the "error" was in fact a trap caused by calling `ret` then
            // this is normal operation and we should return the value captured
            // in the Runtime result field.
            let downcasted_error = host_error.downcast_ref::<Error>();
            match downcasted_error {
                Some(Error::Ret(ref _ret_urefs)) => {
                    return self.take_host_buffer().ok_or(Error::ExpectedReturnValue);
                }
                Some(error) => return Err(error.clone()),
                None => return Err(Error::Interpreter(host_error.to_string())),
            }
        }
        Err(Error::Interpreter(error.into()))
    }

    /// Calls contract living under a `key`, with supplied `args`.
    pub fn call_contract(
        &mut self,
        contract_hash: ContractHash,
        entry_point_name: &str,
        args: RuntimeArgs,
    ) -> Result<CLValue, Error> {
        let key = contract_hash.into();
        let contract = match self.context.read_gs(&key)? {
            Some(StoredValue::Contract(contract)) => contract,
            Some(_) => {
                return Err(Error::InvalidContract(contract_hash));
            }
            None => return Err(Error::KeyNotFound(key)),
        };

        let contract_entry_point = contract
            .entry_point(entry_point_name)
            .cloned()
            .ok_or_else(|| Error::NoSuchMethod(entry_point_name.to_owned()))?;

        let contract_package_hash = contract.contract_package_hash();

        let contract_package = match self.context.read_gs(&contract_package_hash.into())? {
            Some(StoredValue::ContractPackage(contract_package)) => contract_package,
            Some(_) => {
                return Err(Error::InvalidContractPackage(contract_package_hash));
            }
            None => return Err(Error::KeyNotFound(key)),
        };

        self.execute_contract(
            contract_package,
            contract_hash,
            contract,
            contract_entry_point,
            args,
        )
    }

    /// Calls `version` of the contract living at `key`, invoking `method` with
    /// supplied `args`. This function also checks the args conform with the
    /// types given in the contract header.
    pub fn call_versioned_contract(
        &mut self,
        contract_package_hash: ContractPackageHash,
        contract_version: Option<ContractVersion>,
        entry_point_name: String,
        args: RuntimeArgs,
    ) -> Result<CLValue, Error> {
        let contract_package_key = contract_package_hash.into();
        let contract_package = match self.context.read_gs(&contract_package_key)? {
            Some(StoredValue::ContractPackage(contract_package)) => contract_package,
            Some(_) => {
                return Err(Error::InvalidContractPackage(contract_package_hash));
            }
            None => return Err(Error::KeyNotFound(contract_package_key)),
        };

        let contract_version_key = match contract_version {
            Some(version) => {
                ContractVersionKey::new(self.context.protocol_version().value().major, version)
            }
            None => match contract_package.current_contract_version() {
                Some(v) => v,
                None => return Err(Error::NoActiveContractVersions(contract_package_hash)),
            },
        };

        // Get contract entry point hash
        let contract_hash = contract_package
            .lookup_contract_hash(contract_version_key)
            .cloned()
            .ok_or(Error::InvalidContractVersion(contract_version_key))?;

        // Get contract data
        let contract_key = contract_hash.into();
        let contract = match self.context.read_gs(&contract_key)? {
            Some(StoredValue::Contract(contract)) => contract,
            Some(_) => {
                return Err(Error::InvalidContract(contract_hash));
            }
            None => return Err(Error::KeyNotFound(contract_key)),
        };

        let contract_entry_point = contract
            .entry_point(&entry_point_name)
            .cloned()
            .ok_or_else(|| Error::NoSuchMethod(entry_point_name.to_owned()))?;

        self.execute_contract(
            contract_package,
            contract_hash,
            contract,
            contract_entry_point,
            args,
        )
    }

    fn get_context_key_for_contract_call(
        &self,
        contract_hash: ContractHash,
        entry_point: &EntryPoint,
    ) -> Result<Key, Error> {
        let current = self.context.entry_point_type();
        let next = entry_point.entry_point_type();
        match (current, next) {
            (EntryPointType::Contract, EntryPointType::Session) => {
                // Session code can't be called from Contract code for security reasons.
                Err(Error::InvalidContext)
            }
            (EntryPointType::Session, EntryPointType::Session) => {
                // Session code called from session reuses current base key
                Ok(self.context.base_key())
            }
            (EntryPointType::Session, EntryPointType::Contract)
            | (EntryPointType::Contract, EntryPointType::Contract) => Ok(contract_hash.into()),
        }
    }

    fn try_get_memory(&self) -> Result<&MemoryRef, Error> {
        self.memory.as_ref().ok_or(Error::WasmPreprocessing(
            PreprocessingError::MissingMemorySection,
        ))
    }

    fn try_get_module(&self) -> Result<&Module, Error> {
        self.module
            .as_ref()
            .ok_or(Error::WasmPreprocessing(PreprocessingError::MissingModule))
    }

    fn try_get_stack(&self) -> Result<&RuntimeStack, Error> {
        self.stack.as_ref().ok_or(Error::MissingRuntimeStack)
    }

    fn execute_contract(
        &mut self,
        contract_package: ContractPackage,
        contract_hash: ContractHash,
        contract: Contract,
        entry_point: EntryPoint,
        args: RuntimeArgs,
    ) -> Result<CLValue, Error> {
        // if public, allowed
        // if not public, restricted to user group access
        self.validate_group_membership(&contract_package, entry_point.access())?;

        // TODO: plan for 2.0 extra information stating required argument and add chainspec
        // variable ensure args type(s) match defined args of entry point
        // for (param_name, param) in entry_point_args_lookup {
        //     if let Some(named_arg) = args_lookup.get(param_name) {
        //         if param.cl_type() != named_arg.cl_value().cl_type() {
        //             return Err(Error::type_mismatch(
        //                 param.cl_type().clone(),
        //                 named_arg.cl_value().cl_type().clone(),
        //             ));
        //         }
        //     }
        //     // TODO we may add required field in 2.0 and enforce this
        //     // else if !param.cl_type().is_option() {
        //     //     return Err(Error::MissingArgument {
        //     //         name: param.name().to_string(),
        //     //     });
        //     // }
        // }
        //}

        // if session the caller's context
        // else the called contract's context
        let context_key = self.get_context_key_for_contract_call(contract_hash, &entry_point)?;
        let protocol_version = self.context.protocol_version();

        // Check for major version compatibility before calling
        if !contract.is_compatible_protocol_version(protocol_version) {
            return Err(Error::IncompatibleProtocolMajorVersion {
                actual: contract.protocol_version().value().major,
                expected: protocol_version.value().major,
            });
        }

        let (mut named_keys, mut access_rights) = match entry_point.entry_point_type() {
            EntryPointType::Session => (
                self.context.account().named_keys().clone(),
                self.context.account().extract_access_rights(),
            ),
            EntryPointType::Contract => (
                contract.named_keys().clone(),
                contract.extract_access_rights(contract_hash),
            ),
        };

        let stack = {
            let mut stack = self.try_get_stack()?.clone();

            let call_stack_element = match entry_point.entry_point_type() {
                EntryPointType::Session => CallStackElement::stored_session(
                    self.context.account().account_hash(),
                    contract.contract_package_hash(),
                    contract_hash,
                ),
                EntryPointType::Contract => CallStackElement::stored_contract(
                    contract.contract_package_hash(),
                    contract_hash,
                ),
            };
            stack.push(call_stack_element)?;

            stack
        };

        // Determines if this call originated from the system account based on a first
        // element of the call stack.
        let is_system_account = self.context.get_caller() == PublicKey::System.to_account_hash();
        // Is the immediate caller a system contract, such as when the auction calls the mint.
        let is_caller_system_contract =
            self.is_system_contract(self.context.access_rights().context_key())?;
        // Checks if the contract we're about to call is a system contract.
        let is_calling_system_contract = self.is_system_contract(context_key)?;
        // uref attenuation is necessary in the following circumstances:
        //   the originating account (aka the caller) is not the system account and
        //   the immediate caller is either a normal account or a normal contract and
        //   the target contract about to be called is a normal contract
        let should_attenuate_urefs =
            !is_system_account && !is_caller_system_contract && !is_calling_system_contract;

        let context_args = if should_attenuate_urefs {
            // Main purse URefs should be attenuated only when a non-system contract is executed by
            // a non-system account to avoid possible phishing attack scenarios.
            utils::attenuate_uref_in_args(
                args,
                self.context.account().main_purse().addr(),
                AccessRights::WRITE,
            )?
        } else {
            args
        };

        let extended_access_rights = {
            let mut all_urefs = vec![];
            for arg in context_args.to_values() {
                let urefs = utils::extract_urefs(arg)?;
                if !is_caller_system_contract || !is_calling_system_contract {
                    for uref in &urefs {
                        self.context.validate_uref(uref)?;
                    }
                }
                all_urefs.extend(urefs);
            }
            all_urefs
        };

        access_rights.extend(&extended_access_rights);

        if self.is_mint(context_key) {
            return self.call_host_mint(
                entry_point.name(),
                &mut named_keys,
                &context_args,
                access_rights,
                stack,
            );
        } else if self.is_handle_payment(context_key) {
            return self.call_host_handle_payment(
                entry_point.name(),
                &mut named_keys,
                &context_args,
                access_rights,
                stack,
            );
        } else if self.is_auction(context_key) {
            return self.call_host_auction(
                entry_point.name(),
                &mut named_keys,
                &context_args,
                access_rights,
                stack,
            );
        }

        let module: Module = {
            let wasm_key = contract.contract_wasm_key();

            let contract_wasm: ContractWasm = match self.context.read_gs(&wasm_key)? {
                Some(StoredValue::ContractWasm(contract_wasm)) => contract_wasm,
                Some(_) => return Err(Error::InvalidContractWasm(contract.contract_wasm_hash())),
                None => return Err(Error::KeyNotFound(context_key)),
            };

            parity_wasm::deserialize_buffer(contract_wasm.bytes())?
        };

        let context = self.context.new_from_self(
            context_key,
            entry_point.entry_point_type(),
            &mut named_keys,
            access_rights,
            context_args,
        );
        let protocol_version = self.context.protocol_version();
        let (instance, memory) = utils::instance_and_memory(
            module.clone(),
            protocol_version,
            self.config.wasm_config(),
        )?;
        let runtime = &mut Runtime::new_invocation_runtime(self, context, module, memory, stack);

        let result = instance.invoke_export(entry_point.name(), &[], runtime);

        // The `runtime`'s context was initialized with our counter from before the call and any gas
        // charged by the sub-call was added to its counter - so let's copy the correct value of the
        // counter from there to our counter.
        self.context.set_gas_counter(runtime.context.gas_counter());

        {
            let transfers = self.context.transfers_mut();
            *transfers = runtime.context.transfers().to_owned();
        }

        let error = match result {
            Err(error) => error,
            // If `Ok` and the `host_buffer` is `None`, the contract's execution succeeded but did
            // not explicitly call `runtime::ret()`.  Treat as though the execution returned the
            // unit type `()` as per Rust functions which don't specify a return value.
            Ok(_) => {
                if self.context.entry_point_type() == EntryPointType::Session
                    && runtime.context.entry_point_type() == EntryPointType::Session
                {
                    // Overwrites parent's named keys with child's new named key but only when
                    // running session code.
                    *self.context.named_keys_mut() = runtime.context.named_keys().clone();
                }
                self.context
                    .set_remaining_spending_limit(runtime.context.remaining_spending_limit());
                return Ok(runtime.take_host_buffer().unwrap_or(CLValue::from_t(())?));
            }
        };

        if let Some(host_error) = error.as_host_error() {
            // If the "error" was in fact a trap caused by calling `ret` then this is normal
            // operation and we should return the value captured in the Runtime result field.
            let downcasted_error = host_error.downcast_ref::<Error>();
            match downcasted_error {
                Some(Error::Ret(ref ret_urefs)) => {
                    // Insert extra urefs returned from call.
                    // Those returned URef's are guaranteed to be valid as they were already
                    // validated in the `ret` call inside context we ret from.
                    self.context.access_rights_extend(ret_urefs);

                    if self.context.entry_point_type() == EntryPointType::Session
                        && runtime.context.entry_point_type() == EntryPointType::Session
                    {
                        // Overwrites parent's named keys with child's new named keys but only when
                        // running session code.
                        *self.context.named_keys_mut() = runtime.context.named_keys().clone();
                    }

                    // Stored contracts are expected to always call a `ret` function, otherwise it's
                    // an error.
                    return runtime.take_host_buffer().ok_or(Error::ExpectedReturnValue);
                }
                Some(error) => return Err(error.clone()),
                None => return Err(Error::Interpreter(host_error.to_string())),
            }
        }

        Err(Error::Interpreter(error.into()))
    }

    fn call_contract_host_buffer(
        &mut self,
        contract_hash: ContractHash,
        entry_point_name: &str,
        args_bytes: Vec<u8>,
        result_size_ptr: u32,
        scoped_instrumenter: &mut ScopedInstrumenter,
    ) -> Result<Result<(), ApiError>, Error> {
        // Exit early if the host buffer is already occupied
        if let Err(err) = self.check_host_buffer() {
            return Ok(Err(err));
        }
        let args: RuntimeArgs = bytesrepr::deserialize(args_bytes)?;
        scoped_instrumenter.pause();
        let result = self.call_contract(contract_hash, entry_point_name, args)?;
        scoped_instrumenter.unpause();
        self.manage_call_contract_host_buffer(result_size_ptr, result)
    }

    fn call_versioned_contract_host_buffer(
        &mut self,
        contract_package_hash: ContractPackageHash,
        contract_version: Option<ContractVersion>,
        entry_point_name: String,
        args_bytes: Vec<u8>,
        result_size_ptr: u32,
        scoped_instrumenter: &mut ScopedInstrumenter,
    ) -> Result<Result<(), ApiError>, Error> {
        // Exit early if the host buffer is already occupied
        if let Err(err) = self.check_host_buffer() {
            return Ok(Err(err));
        }
        let args: RuntimeArgs = bytesrepr::deserialize(args_bytes)?;
        scoped_instrumenter.pause();
        let result = self.call_versioned_contract(
            contract_package_hash,
            contract_version,
            entry_point_name,
            args,
        )?;
        scoped_instrumenter.unpause();
        self.manage_call_contract_host_buffer(result_size_ptr, result)
    }

    fn check_host_buffer(&mut self) -> Result<(), ApiError> {
        if !self.can_write_to_host_buffer() {
            Err(ApiError::HostBufferFull)
        } else {
            Ok(())
        }
    }

    fn manage_call_contract_host_buffer(
        &mut self,
        result_size_ptr: u32,
        result: CLValue,
    ) -> Result<Result<(), ApiError>, Error> {
        let result_size = result.inner_bytes().len() as u32; // considered to be safe

        // leave the host buffer set to `None` if there's nothing to write there
        if result_size != 0 {
            if let Err(error) = self.write_host_buffer(result) {
                return Ok(Err(error));
            }
        }

        let result_size_bytes = result_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self
            .try_get_memory()?
            .set(result_size_ptr, &result_size_bytes)
        {
            return Err(Error::Interpreter(error.into()));
        }

        Ok(Ok(()))
    }

    fn load_named_keys(
        &mut self,
        total_keys_ptr: u32,
        result_size_ptr: u32,
        scoped_instrumenter: &mut ScopedInstrumenter,
    ) -> Result<Result<(), ApiError>, Trap> {
        scoped_instrumenter.add_property(
            "names_total_length",
            self.context
                .named_keys()
                .keys()
                .map(|name| name.len())
                .sum::<usize>(),
        );

        if !self.can_write_to_host_buffer() {
            // Exit early if the host buffer is already occupied
            return Ok(Err(ApiError::HostBufferFull));
        }

        let total_keys = self.context.named_keys().len() as u32;
        let total_keys_bytes = total_keys.to_le_bytes();
        if let Err(error) = self
            .try_get_memory()?
            .set(total_keys_ptr, &total_keys_bytes)
        {
            return Err(Error::Interpreter(error.into()).into());
        }

        if total_keys == 0 {
            // No need to do anything else, we leave host buffer empty.
            return Ok(Ok(()));
        }

        let named_keys =
            CLValue::from_t(self.context.named_keys().clone()).map_err(Error::CLValue)?;

        let length = named_keys.inner_bytes().len() as u32;
        if let Err(error) = self.write_host_buffer(named_keys) {
            return Ok(Err(error));
        }

        let length_bytes = length.to_le_bytes();
        if let Err(error) = self.try_get_memory()?.set(result_size_ptr, &length_bytes) {
            return Err(Error::Interpreter(error.into()).into());
        }

        Ok(Ok(()))
    }

    fn create_contract_package(
        &mut self,
        is_locked: ContractPackageStatus,
    ) -> Result<(ContractPackage, URef), Error> {
        let access_key = self.context.new_unit_uref()?;
        let contract_package = ContractPackage::new(
            access_key,
            ContractVersions::default(),
            DisabledVersions::default(),
            Groups::default(),
            is_locked,
        );

        Ok((contract_package, access_key))
    }

    fn create_contract_package_at_hash(
        &mut self,
        lock_status: ContractPackageStatus,
    ) -> Result<([u8; 32], [u8; 32]), Error> {
        let addr = self.context.new_hash_address()?;
        let (contract_package, access_key) = self.create_contract_package(lock_status)?;
        self.context
            .metered_write_gs_unsafe(Key::Hash(addr), contract_package)?;
        Ok((addr, access_key.addr()))
    }

    fn create_contract_user_group(
        &mut self,
        contract_package_hash: ContractPackageHash,
        label: String,
        num_new_urefs: u32,
        mut existing_urefs: BTreeSet<URef>,
        output_size_ptr: u32,
    ) -> Result<Result<(), ApiError>, Error> {
        let mut contract_package: ContractPackage = self
            .context
            .get_validated_contract_package(contract_package_hash)?;

        let groups = contract_package.groups_mut();
        let new_group = Group::new(label);

        // Ensure group does not already exist
        if groups.get(&new_group).is_some() {
            return Ok(Err(contracts::Error::GroupAlreadyExists.into()));
        }

        // Ensure there are not too many groups
        if groups.len() >= (contracts::MAX_GROUPS as usize) {
            return Ok(Err(contracts::Error::MaxGroupsExceeded.into()));
        }

        // Ensure there are not too many urefs
        let total_urefs: usize = groups.values().map(|urefs| urefs.len()).sum::<usize>()
            + (num_new_urefs as usize)
            + existing_urefs.len();
        if total_urefs > contracts::MAX_TOTAL_UREFS {
            let err = contracts::Error::MaxTotalURefsExceeded;
            return Ok(Err(ApiError::ContractHeader(err as u8)));
        }

        // Proceed with creating user group
        let mut new_urefs = Vec::with_capacity(num_new_urefs as usize);
        for _ in 0..num_new_urefs {
            let u = self.context.new_unit_uref()?;
            new_urefs.push(u);
        }

        for u in new_urefs.iter().cloned() {
            existing_urefs.insert(u);
        }
        groups.insert(new_group, existing_urefs);

        // check we can write to the host buffer
        if let Err(err) = self.check_host_buffer() {
            return Ok(Err(err));
        }
        // create CLValue for return value
        let new_urefs_value = CLValue::from_t(new_urefs)?;
        let value_size = new_urefs_value.inner_bytes().len();
        // write return value to buffer
        if let Err(err) = self.write_host_buffer(new_urefs_value) {
            return Ok(Err(err));
        }
        // Write return value size to output location
        let output_size_bytes = value_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self
            .try_get_memory()?
            .set(output_size_ptr, &output_size_bytes)
        {
            return Err(Error::Interpreter(error.into()));
        }

        // Write updated package to the global state
        self.context
            .metered_write_gs_unsafe(contract_package_hash, contract_package)?;

        Ok(Ok(()))
    }

    #[allow(clippy::too_many_arguments)]
    fn add_contract_version(
        &mut self,
        contract_package_hash: ContractPackageHash,
        entry_points: EntryPoints,
        mut named_keys: NamedKeys,
        output_ptr: u32,
        output_size: usize,
        bytes_written_ptr: u32,
        version_ptr: u32,
    ) -> Result<Result<(), ApiError>, Error> {
        self.context
            .validate_key(&Key::from(contract_package_hash))?;

        let mut contract_package: ContractPackage = self
            .context
            .get_validated_contract_package(contract_package_hash)?;

        let version = contract_package.current_contract_version();

        // Return an error if the contract is locked and has some version associated with it.
        if contract_package.is_locked() && version.is_some() {
            return Err(Error::LockedContract(contract_package_hash));
        }

        let contract_wasm_hash = self.context.new_hash_address()?;
        let contract_wasm = {
            let module_bytes = self.get_module_from_entry_points(&entry_points)?;
            ContractWasm::new(module_bytes)
        };

        let contract_hash = self.context.new_hash_address()?;

        let protocol_version = self.context.protocol_version();
        let major = protocol_version.value().major;

        // TODO: EE-1032 - Implement different ways of carrying on existing named keys
        if let Some(previous_contract_hash) = contract_package.current_contract_hash() {
            let previous_contract: Contract =
                self.context.read_gs_typed(&previous_contract_hash.into())?;

            let mut previous_named_keys = previous_contract.take_named_keys();
            named_keys.append(&mut previous_named_keys);
        }

        let contract = Contract::new(
            contract_package_hash,
            contract_wasm_hash.into(),
            named_keys,
            entry_points,
            protocol_version,
        );

        let insert_contract_result =
            contract_package.insert_contract_version(major, contract_hash.into());

        self.context
            .metered_write_gs_unsafe(Key::Hash(contract_wasm_hash), contract_wasm)?;
        self.context
            .metered_write_gs_unsafe(Key::Hash(contract_hash), contract)?;
        self.context
            .metered_write_gs_unsafe(contract_package_hash, contract_package)?;

        // return contract key to caller
        {
            let key_bytes = match contract_hash.to_bytes() {
                Ok(bytes) => bytes,
                Err(error) => return Ok(Err(error.into())),
            };

            // `output_size` must be >= actual length of serialized Key bytes
            if output_size < key_bytes.len() {
                return Ok(Err(ApiError::BufferTooSmall));
            }

            // Set serialized Key bytes into the output buffer
            if let Err(error) = self.try_get_memory()?.set(output_ptr, &key_bytes) {
                return Err(Error::Interpreter(error.into()));
            }

            // Following cast is assumed to be safe
            let bytes_size = key_bytes.len() as u32;
            let size_bytes = bytes_size.to_le_bytes(); // Wasm is little-endian
            if let Err(error) = self.try_get_memory()?.set(bytes_written_ptr, &size_bytes) {
                return Err(Error::Interpreter(error.into()));
            }

            let version_value: u32 = insert_contract_result.contract_version();
            let version_bytes = version_value.to_le_bytes();
            if let Err(error) = self.try_get_memory()?.set(version_ptr, &version_bytes) {
                return Err(Error::Interpreter(error.into()));
            }
        }

        Ok(Ok(()))
    }

    fn disable_contract_version(
        &mut self,
        contract_package_hash: ContractPackageHash,
        contract_hash: ContractHash,
    ) -> Result<Result<(), ApiError>, Error> {
        let contract_package_key = contract_package_hash.into();
        self.context.validate_key(&contract_package_key)?;

        let mut contract_package: ContractPackage = self
            .context
            .get_validated_contract_package(contract_package_hash)?;

        // Return an error in trying to disable the (singular) version of a locked contract.
        if contract_package.is_locked() {
            return Err(Error::LockedContract(contract_package_hash));
        }

        if let Err(err) = contract_package.disable_contract_version(contract_hash) {
            return Ok(Err(err.into()));
        }

        self.context
            .metered_write_gs_unsafe(contract_package_key, contract_package)?;

        Ok(Ok(()))
    }

    /// Writes function address (`hash_bytes`) into the Wasm memory (at
    /// `dest_ptr` pointer).
    fn function_address(&mut self, hash_bytes: [u8; 32], dest_ptr: u32) -> Result<(), Trap> {
        self.try_get_memory()?
            .set(dest_ptr, &hash_bytes)
            .map_err(|e| Error::Interpreter(e.into()).into())
    }

    /// Generates new unforgable reference and adds it to the context's
    /// access_rights set.
    fn new_uref(&mut self, uref_ptr: u32, value_ptr: u32, value_size: u32) -> Result<(), Trap> {
        let cl_value = self.cl_value_from_mem(value_ptr, value_size)?; // read initial value from memory
        let uref = self.context.new_uref(StoredValue::CLValue(cl_value))?;
        self.try_get_memory()?
            .set(uref_ptr, &uref.into_bytes().map_err(Error::BytesRepr)?)
            .map_err(|e| Error::Interpreter(e.into()).into())
    }

    /// Writes `value` under `key` in GlobalState.
    fn write(
        &mut self,
        key_ptr: u32,
        key_size: u32,
        value_ptr: u32,
        value_size: u32,
    ) -> Result<(), Trap> {
        let key = self.key_from_mem(key_ptr, key_size)?;
        let cl_value = self.cl_value_from_mem(value_ptr, value_size)?;
        self.context
            .metered_write_gs(key, cl_value)
            .map_err(Into::into)
    }

    /// Records a transfer.
    fn record_transfer(
        &mut self,
        maybe_to: Option<AccountHash>,
        source: URef,
        target: URef,
        amount: U512,
        id: Option<u64>,
    ) -> Result<(), Error> {
        if self.context.base_key() != Key::from(self.context.get_system_contract(MINT)?) {
            return Err(Error::InvalidContext);
        }

        if self.context.phase() != Phase::Session {
            return Ok(());
        }

        let transfer_addr = self.context.new_transfer_addr()?;
        let transfer = {
            let deploy_hash: DeployHash = self.context.get_deploy_hash();
            let from: AccountHash = self.context.account().account_hash();
            let fee: U512 = U512::zero(); // TODO
            Transfer::new(deploy_hash, from, maybe_to, source, target, amount, fee, id)
        };
        {
            let transfers = self.context.transfers_mut();
            transfers.push(transfer_addr);
        }
        self.context
            .write_transfer(Key::Transfer(transfer_addr), transfer);
        Ok(())
    }

    /// Records given auction info at a given era id
    fn record_era_info(&mut self, era_id: EraId, era_info: EraInfo) -> Result<(), Error> {
        if self.context.base_key() != Key::from(self.context.get_system_contract(AUCTION)?) {
            return Err(Error::InvalidContext);
        }

        if self.context.phase() != Phase::Session {
            return Ok(());
        }

        self.context.write_era_info(Key::EraInfo(era_id), era_info);

        Ok(())
    }

    /// Adds `value` to the cell that `key` points at.
    fn add(
        &mut self,
        key_ptr: u32,
        key_size: u32,
        value_ptr: u32,
        value_size: u32,
    ) -> Result<(), Trap> {
        let key = self.key_from_mem(key_ptr, key_size)?;
        let cl_value = self.cl_value_from_mem(value_ptr, value_size)?;
        self.context
            .metered_add_gs(key, cl_value)
            .map_err(Into::into)
    }

    /// Reads value from the GS living under key specified by `key_ptr` and
    /// `key_size`. Wasm and host communicate through memory that Wasm
    /// module exports. If contract wants to pass data to the host, it has
    /// to tell it [the host] where this data lives in the exported memory
    /// (pass its pointer and length).
    fn read(
        &mut self,
        key_ptr: u32,
        key_size: u32,
        output_size_ptr: u32,
    ) -> Result<Result<(), ApiError>, Trap> {
        if !self.can_write_to_host_buffer() {
            // Exit early if the host buffer is already occupied
            return Ok(Err(ApiError::HostBufferFull));
        }

        let key = self.key_from_mem(key_ptr, key_size)?;
        let cl_value = match self.context.read_gs(&key)? {
            Some(stored_value) => CLValue::try_from(stored_value).map_err(Error::TypeMismatch)?,
            None => return Ok(Err(ApiError::ValueNotFound)),
        };

        let value_size = cl_value.inner_bytes().len() as u32;
        if let Err(error) = self.write_host_buffer(cl_value) {
            return Ok(Err(error));
        }

        let value_bytes = value_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self.try_get_memory()?.set(output_size_ptr, &value_bytes) {
            return Err(Error::Interpreter(error.into()).into());
        }

        Ok(Ok(()))
    }

    /// Reverts contract execution with a status specified.
    fn revert(&mut self, status: u32) -> Trap {
        Error::Revert(status.into()).into()
    }

    fn add_associated_key(
        &mut self,
        account_hash_ptr: u32,
        account_hash_size: usize,
        weight_value: u8,
    ) -> Result<i32, Trap> {
        let account_hash = {
            // Account hash as serialized bytes
            let source_serialized = self.bytes_from_mem(account_hash_ptr, account_hash_size)?;
            // Account hash deserialized
            let source: AccountHash =
                bytesrepr::deserialize(source_serialized).map_err(Error::BytesRepr)?;
            source
        };
        let weight = Weight::new(weight_value);

        match self.context.add_associated_key(account_hash, weight) {
            Ok(_) => Ok(0),
            // This relies on the fact that `AddKeyFailure` is represented as
            // i32 and first variant start with number `1`, so all other variants
            // are greater than the first one, so it's safe to assume `0` is success,
            // and any error is greater than 0.
            Err(Error::AddKeyFailure(e)) => Ok(e as i32),
            // Any other variant just pass as `Trap`
            Err(e) => Err(e.into()),
        }
    }

    fn remove_associated_key(
        &mut self,
        account_hash_ptr: u32,
        account_hash_size: usize,
    ) -> Result<i32, Trap> {
        let account_hash = {
            // Account hash as serialized bytes
            let source_serialized = self.bytes_from_mem(account_hash_ptr, account_hash_size)?;
            // Account hash deserialized
            let source: AccountHash =
                bytesrepr::deserialize(source_serialized).map_err(Error::BytesRepr)?;
            source
        };
        match self.context.remove_associated_key(account_hash) {
            Ok(_) => Ok(0),
            Err(Error::RemoveKeyFailure(e)) => Ok(e as i32),
            Err(e) => Err(e.into()),
        }
    }

    fn update_associated_key(
        &mut self,
        account_hash_ptr: u32,
        account_hash_size: usize,
        weight_value: u8,
    ) -> Result<i32, Trap> {
        let account_hash = {
            // Account hash as serialized bytes
            let source_serialized = self.bytes_from_mem(account_hash_ptr, account_hash_size)?;
            // Account hash deserialized
            let source: AccountHash =
                bytesrepr::deserialize(source_serialized).map_err(Error::BytesRepr)?;
            source
        };
        let weight = Weight::new(weight_value);

        match self.context.update_associated_key(account_hash, weight) {
            Ok(_) => Ok(0),
            // This relies on the fact that `UpdateKeyFailure` is represented as
            // i32 and first variant start with number `1`, so all other variants
            // are greater than the first one, so it's safe to assume `0` is success,
            // and any error is greater than 0.
            Err(Error::UpdateKeyFailure(e)) => Ok(e as i32),
            // Any other variant just pass as `Trap`
            Err(e) => Err(e.into()),
        }
    }

    fn set_action_threshold(
        &mut self,
        action_type_value: u32,
        threshold_value: u8,
    ) -> Result<i32, Trap> {
        match ActionType::try_from(action_type_value) {
            Ok(action_type) => {
                let threshold = Weight::new(threshold_value);
                match self.context.set_action_threshold(action_type, threshold) {
                    Ok(_) => Ok(0),
                    Err(Error::SetThresholdFailure(e)) => Ok(e as i32),
                    Err(e) => Err(e.into()),
                }
            }
            Err(_) => Err(Trap::new(TrapKind::Unreachable)),
        }
    }

    /// Looks up the public mint contract key in the context's protocol data.
    ///
    /// Returned URef is already attenuated depending on the calling account.
    fn get_mint_contract(&self) -> Result<ContractHash, Error> {
        self.context.get_system_contract(MINT)
    }

    /// Looks up the public handle payment contract key in the context's protocol data.
    ///
    /// Returned URef is already attenuated depending on the calling account.
    fn get_handle_payment_contract(&self) -> Result<ContractHash, Error> {
        self.context.get_system_contract(HANDLE_PAYMENT)
    }

    /// Looks up the public standard payment contract key in the context's protocol data.
    ///
    /// Returned URef is already attenuated depending on the calling account.
    fn get_standard_payment_contract(&self) -> Result<ContractHash, Error> {
        self.context.get_system_contract(STANDARD_PAYMENT)
    }

    /// Looks up the public auction contract key in the context's protocol data.
    ///
    /// Returned URef is already attenuated depending on the calling account.
    fn get_auction_contract(&self) -> Result<ContractHash, Error> {
        self.context.get_system_contract(AUCTION)
    }

    /// Calls the `read_base_round_reward` method on the mint contract at the given mint
    /// contract key
    fn mint_read_base_round_reward(
        &mut self,
        mint_contract_hash: ContractHash,
    ) -> Result<U512, Error> {
        let gas_counter = self.gas_counter();
        let call_result = self.call_contract(
            mint_contract_hash,
            mint::METHOD_READ_BASE_ROUND_REWARD,
            RuntimeArgs::default(),
        );
        self.set_gas_counter(gas_counter);

        let reward = call_result?.into_t()?;
        Ok(reward)
    }

    /// Calls the `mint` method on the mint contract at the given mint
    /// contract key
    fn mint_mint(&mut self, mint_contract_hash: ContractHash, amount: U512) -> Result<URef, Error> {
        let gas_counter = self.gas_counter();
        let runtime_args = {
            let mut runtime_args = RuntimeArgs::new();
            runtime_args.insert(mint::ARG_AMOUNT, amount)?;
            runtime_args
        };
        let call_result = self.call_contract(mint_contract_hash, mint::METHOD_MINT, runtime_args);
        self.set_gas_counter(gas_counter);

        let result: Result<URef, mint::Error> = call_result?.into_t()?;
        Ok(result.map_err(system::Error::from)?)
    }

    /// Calls the `reduce_total_supply` method on the mint contract at the given mint
    /// contract key
    fn mint_reduce_total_supply(
        &mut self,
        mint_contract_hash: ContractHash,
        amount: U512,
    ) -> Result<(), Error> {
        let gas_counter = self.gas_counter();
        let runtime_args = {
            let mut runtime_args = RuntimeArgs::new();
            runtime_args.insert(mint::ARG_AMOUNT, amount)?;
            runtime_args
        };
        let call_result = self.call_contract(
            mint_contract_hash,
            mint::METHOD_REDUCE_TOTAL_SUPPLY,
            runtime_args,
        );
        self.set_gas_counter(gas_counter);

        let result: Result<(), mint::Error> = call_result?.into_t()?;
        Ok(result.map_err(system::Error::from)?)
    }

    /// Calls the "create" method on the mint contract at the given mint
    /// contract key
    fn mint_create(&mut self, mint_contract_hash: ContractHash) -> Result<URef, Error> {
        let result =
            self.call_contract(mint_contract_hash, mint::METHOD_CREATE, RuntimeArgs::new());
        let purse = result?.into_t()?;
        Ok(purse)
    }

    fn create_purse(&mut self) -> Result<URef, Error> {
        let _scoped_host_function_flag = self.host_function_flag.enter_host_function_scope();
        self.mint_create(self.get_mint_contract()?)
    }

    /// Calls the "transfer" method on the mint contract at the given mint
    /// contract key
    fn mint_transfer(
        &mut self,
        mint_contract_hash: ContractHash,
        to: Option<AccountHash>,
        source: URef,
        target: URef,
        amount: U512,
        id: Option<u64>,
    ) -> Result<Result<(), mint::Error>, Error> {
        self.context.validate_uref(&source)?;

        let args_values = {
            let mut runtime_args = RuntimeArgs::new();
            runtime_args.insert(mint::ARG_TO, to)?;
            runtime_args.insert(mint::ARG_SOURCE, source)?;
            runtime_args.insert(mint::ARG_TARGET, target)?;
            runtime_args.insert(mint::ARG_AMOUNT, amount)?;
            runtime_args.insert(mint::ARG_ID, id)?;
            runtime_args
        };

        let gas_counter = self.gas_counter();
        let call_result =
            self.call_contract(mint_contract_hash, mint::METHOD_TRANSFER, args_values);
        self.set_gas_counter(gas_counter);

        Ok(call_result?.into_t()?)
    }

    /// Creates a new account at a given public key, transferring a given amount
    /// of motes from the given source purse to the new account's purse.
    fn transfer_to_new_account(
        &mut self,
        source: URef,
        target: AccountHash,
        amount: U512,
        id: Option<u64>,
    ) -> Result<TransferResult, Error> {
        let mint_contract_hash = self.get_mint_contract()?;

        let target_key = Key::Account(target);

        // A precondition check that verifies that the transfer can be done
        // as the source purse has enough funds to cover the transfer.
        if amount > self.get_balance(source)?.unwrap_or_default() {
            return Ok(Err(mint::Error::InsufficientFunds.into()));
        }

        let target_purse = self.mint_create(mint_contract_hash)?;

        if source == target_purse {
            return Ok(Err(mint::Error::EqualSourceAndTarget.into()));
        }

        let result = self.mint_transfer(
            mint_contract_hash,
            Some(target),
            source,
            target_purse.with_access_rights(AccessRights::ADD),
            amount,
            id,
        );

        // We granted a temporary access rights bit to newly created main purse as part of
        // `mint_create` call, and we need to remove it to avoid leakage of access rights.

        self.context
            .remove_access(target_purse.addr(), target_purse.access_rights());

        match result? {
            Ok(()) => {
                let account = Account::create(target, Default::default(), target_purse);
                self.context.write_account(target_key, account)?;
                Ok(Ok(TransferredTo::NewAccount))
            }
            Err(mint_error) => Ok(Err(mint_error.into())),
        }
    }

    /// Transferring a given amount of motes from the given source purse to the
    /// new account's purse. Requires that the [`URef`]s have already
    /// been created by the mint contract (or are the genesis account's).
    fn transfer_to_existing_account(
        &mut self,
        to: Option<AccountHash>,
        source: URef,
        target: URef,
        amount: U512,
        id: Option<u64>,
    ) -> Result<TransferResult, Error> {
        let mint_contract_key = self.get_mint_contract()?;

        match self.mint_transfer(mint_contract_key, to, source, target, amount, id)? {
            Ok(()) => Ok(Ok(TransferredTo::ExistingAccount)),
            Err(error) => Ok(Err(error.into())),
        }
    }

    /// Transfers `amount` of motes from default purse of the account to
    /// `target` account. If that account does not exist, creates one.
    fn transfer_to_account(
        &mut self,
        target: AccountHash,
        amount: U512,
        id: Option<u64>,
    ) -> Result<TransferResult, Error> {
        let source = self.context.get_main_purse()?;
        self.transfer_from_purse_to_account(source, target, amount, id)
    }

    /// Transfers `amount` of motes from `source` purse to `target` account.
    /// If that account does not exist, creates one.
    fn transfer_from_purse_to_account(
        &mut self,
        source: URef,
        target: AccountHash,
        amount: U512,
        id: Option<u64>,
    ) -> Result<TransferResult, Error> {
        let _scoped_host_function_flag = self.host_function_flag.enter_host_function_scope();

        let target_key = Key::Account(target);
        // Look up the account at the given public key's address
        match self.context.read_account(&target_key)? {
            None => {
                // If no account exists, create a new account and transfer the amount to its
                // purse.
                self.transfer_to_new_account(source, target, amount, id)
            }
            Some(StoredValue::Account(account)) => {
                // Attenuate the target main purse
                let target_uref = account.main_purse_add_only();

                if source.with_access_rights(AccessRights::ADD) == target_uref {
                    return Ok(Ok(TransferredTo::ExistingAccount));
                }

                // Upsert ADD access to caller on target allowing deposit of motes; this will be
                // revoked after the transfer is completed if caller did not already have ADD access
                let granted_access = self.context.grant_access(target_uref);

                // If an account exists, transfer the amount to its purse
                let transfer_result = self.transfer_to_existing_account(
                    Some(target),
                    source,
                    target_uref,
                    amount,
                    id,
                );

                // Remove from caller temporarily granted ADD access on target.
                if let GrantedAccess::Granted {
                    uref_addr,
                    newly_granted_access_rights,
                } = granted_access
                {
                    self.context
                        .remove_access(uref_addr, newly_granted_access_rights)
                }
                transfer_result
            }
            Some(_) => {
                // If some other value exists, return an error
                Err(Error::AccountNotFound(target_key))
            }
        }
    }

    /// Transfers `amount` of motes from `source` purse to `target` purse.
    #[allow(clippy::too_many_arguments)]
    fn transfer_from_purse_to_purse(
        &mut self,
        source_ptr: u32,
        source_size: u32,
        target_ptr: u32,
        target_size: u32,
        amount_ptr: u32,
        amount_size: u32,
        id_ptr: u32,
        id_size: u32,
    ) -> Result<Result<(), mint::Error>, Error> {
        let source: URef = {
            let bytes = self.bytes_from_mem(source_ptr, source_size as usize)?;
            bytesrepr::deserialize(bytes).map_err(Error::BytesRepr)?
        };

        let target: URef = {
            let bytes = self.bytes_from_mem(target_ptr, target_size as usize)?;
            bytesrepr::deserialize(bytes).map_err(Error::BytesRepr)?
        };

        let amount: U512 = {
            let bytes = self.bytes_from_mem(amount_ptr, amount_size as usize)?;
            bytesrepr::deserialize(bytes).map_err(Error::BytesRepr)?
        };

        let id: Option<u64> = {
            let bytes = self.bytes_from_mem(id_ptr, id_size as usize)?;
            bytesrepr::deserialize(bytes).map_err(Error::BytesRepr)?
        };

        self.context.validate_uref(&source)?;

        let mint_contract_key = self.get_mint_contract()?;

        match self.mint_transfer(mint_contract_key, None, source, target, amount, id)? {
            Ok(()) => Ok(Ok(())),
            Err(mint_error) => Ok(Err(mint_error)),
        }
    }

    fn get_balance(&mut self, purse: URef) -> Result<Option<U512>, Error> {
        let maybe_value = self.context.read_gs_direct(&Key::Balance(purse.addr()))?;
        match maybe_value {
            Some(StoredValue::CLValue(value)) => {
                let value = CLValue::into_t(value)?;
                Ok(Some(value))
            }
            Some(_) => Err(Error::UnexpectedStoredValueVariant),
            None => Ok(None),
        }
    }

    fn get_balance_host_buffer(
        &mut self,
        purse_ptr: u32,
        purse_size: usize,
        output_size_ptr: u32,
    ) -> Result<Result<(), ApiError>, Error> {
        if !self.can_write_to_host_buffer() {
            // Exit early if the host buffer is already occupied
            return Ok(Err(ApiError::HostBufferFull));
        }

        let purse: URef = {
            let bytes = self.bytes_from_mem(purse_ptr, purse_size)?;
            match bytesrepr::deserialize(bytes) {
                Ok(purse) => purse,
                Err(error) => return Ok(Err(error.into())),
            }
        };

        let balance = match self.get_balance(purse)? {
            Some(balance) => balance,
            None => return Ok(Err(ApiError::InvalidPurse)),
        };

        let balance_cl_value = match CLValue::from_t(balance) {
            Ok(cl_value) => cl_value,
            Err(error) => return Ok(Err(error.into())),
        };

        let balance_size = balance_cl_value.inner_bytes().len() as i32;
        if let Err(error) = self.write_host_buffer(balance_cl_value) {
            return Ok(Err(error));
        }

        let balance_size_bytes = balance_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self
            .try_get_memory()?
            .set(output_size_ptr, &balance_size_bytes)
        {
            return Err(Error::Interpreter(error.into()));
        }

        Ok(Ok(()))
    }

    fn get_system_contract(
        &mut self,
        system_contract_index: u32,
        dest_ptr: u32,
        _dest_size: u32,
    ) -> Result<Result<(), ApiError>, Trap> {
        let contract_hash: ContractHash = match SystemContractType::try_from(system_contract_index)
        {
            Ok(SystemContractType::Mint) => self.get_mint_contract()?,
            Ok(SystemContractType::HandlePayment) => self.get_handle_payment_contract()?,
            Ok(SystemContractType::StandardPayment) => self.get_standard_payment_contract()?,
            Ok(SystemContractType::Auction) => self.get_auction_contract()?,
            Err(error) => return Ok(Err(error)),
        };

        match self.try_get_memory()?.set(dest_ptr, contract_hash.as_ref()) {
            Ok(_) => Ok(Ok(())),
            Err(error) => Err(Error::Interpreter(error.into()).into()),
        }
    }

    /// If host_buffer set, clears the host_buffer and returns value, else None
    pub fn take_host_buffer(&mut self) -> Option<CLValue> {
        self.host_buffer.take()
    }

    /// Checks if a write to host buffer can happen.
    ///
    /// This will check if the host buffer is empty.
    fn can_write_to_host_buffer(&self) -> bool {
        self.host_buffer.is_none()
    }

    /// Overwrites data in host buffer only if it's in empty state
    fn write_host_buffer(&mut self, data: CLValue) -> Result<(), ApiError> {
        match self.host_buffer {
            Some(_) => return Err(ApiError::HostBufferFull),
            None => self.host_buffer = Some(data),
        }
        Ok(())
    }

    fn read_host_buffer(
        &mut self,
        dest_ptr: u32,
        dest_size: usize,
        bytes_written_ptr: u32,
    ) -> Result<Result<(), ApiError>, Error> {
        let (_cl_type, serialized_value) = match self.take_host_buffer() {
            None => return Ok(Err(ApiError::HostBufferEmpty)),
            Some(cl_value) => cl_value.destructure(),
        };

        if serialized_value.len() > u32::max_value() as usize {
            return Ok(Err(ApiError::OutOfMemory));
        }
        if serialized_value.len() > dest_size {
            return Ok(Err(ApiError::BufferTooSmall));
        }

        // Slice data, so if `dest_size` is larger than host_buffer size, it will take host_buffer
        // as whole.
        let sliced_buf = &serialized_value[..cmp::min(dest_size, serialized_value.len())];
        if let Err(error) = self.try_get_memory()?.set(dest_ptr, sliced_buf) {
            return Err(Error::Interpreter(error.into()));
        }

        let bytes_written = sliced_buf.len() as u32;
        let bytes_written_data = bytes_written.to_le_bytes();

        if let Err(error) = self
            .try_get_memory()?
            .set(bytes_written_ptr, &bytes_written_data)
        {
            return Err(Error::Interpreter(error.into()));
        }

        Ok(Ok(()))
    }

    #[cfg(feature = "test-support")]
    fn print(&mut self, text_ptr: u32, text_size: u32) -> Result<(), Trap> {
        let text = self.string_from_mem(text_ptr, text_size)?;
        println!("{}", text);
        Ok(())
    }

    fn get_named_arg_size(
        &mut self,
        name_ptr: u32,
        name_size: usize,
        size_ptr: u32,
    ) -> Result<Result<(), ApiError>, Trap> {
        let name_bytes = self.bytes_from_mem(name_ptr, name_size)?;
        let name = String::from_utf8_lossy(&name_bytes);

        let arg_size = match self.context.args().get(&name) {
            Some(arg) if arg.inner_bytes().len() > u32::max_value() as usize => {
                return Ok(Err(ApiError::OutOfMemory));
            }
            Some(arg) => arg.inner_bytes().len() as u32,
            None => return Ok(Err(ApiError::MissingArgument)),
        };

        let arg_size_bytes = arg_size.to_le_bytes(); // Wasm is little-endian

        if let Err(e) = self.try_get_memory()?.set(size_ptr, &arg_size_bytes) {
            return Err(Error::Interpreter(e.into()).into());
        }

        Ok(Ok(()))
    }

    fn get_named_arg(
        &mut self,
        name_ptr: u32,
        name_size: usize,
        output_ptr: u32,
        output_size: usize,
    ) -> Result<Result<(), ApiError>, Trap> {
        let name_bytes = self.bytes_from_mem(name_ptr, name_size)?;
        let name = String::from_utf8_lossy(&name_bytes);

        let arg = match self.context.args().get(&name) {
            Some(arg) => arg,
            None => return Ok(Err(ApiError::MissingArgument)),
        };

        if arg.inner_bytes().len() > output_size {
            return Ok(Err(ApiError::OutOfMemory));
        }

        if let Err(error) = self
            .try_get_memory()?
            .set(output_ptr, &arg.inner_bytes()[..output_size])
        {
            return Err(Error::Interpreter(error.into()).into());
        }

        Ok(Ok(()))
    }

    /// Enforce group access restrictions (if any) on attempts to call an `EntryPoint`.
    fn validate_group_membership(
        &self,
        package: &ContractPackage,
        access: &EntryPointAccess,
    ) -> Result<(), Error> {
        runtime_context::validate_group_membership(package, access, |uref| {
            self.context.validate_uref(uref).is_ok()
        })
    }

    /// Remove a user group from access to a contract
    fn remove_contract_user_group(
        &mut self,
        package_key: ContractPackageHash,
        label: Group,
    ) -> Result<Result<(), ApiError>, Error> {
        let mut package: ContractPackage =
            self.context.get_validated_contract_package(package_key)?;

        let group_to_remove = Group::new(label);
        let groups = package.groups_mut();

        // Ensure group exists in groups
        if groups.get(&group_to_remove).is_none() {
            return Ok(Err(contracts::Error::GroupDoesNotExist.into()));
        }

        // Remove group if it is not referenced by at least one entry_point in active versions.
        let versions = package.versions();
        for contract_hash in versions.values() {
            let entry_points = {
                let contract: Contract = self.context.read_gs_typed(&Key::from(*contract_hash))?;
                contract.entry_points().clone().take_entry_points()
            };
            for entry_point in entry_points {
                match entry_point.access() {
                    EntryPointAccess::Public => {
                        continue;
                    }
                    EntryPointAccess::Groups(groups) => {
                        if groups.contains(&group_to_remove) {
                            return Ok(Err(contracts::Error::GroupInUse.into()));
                        }
                    }
                }
            }
        }

        if !package.remove_group(&group_to_remove) {
            return Ok(Err(contracts::Error::GroupInUse.into()));
        }

        // Write updated package to the global state
        self.context.metered_write_gs_unsafe(package_key, package)?;
        Ok(Ok(()))
    }

    #[allow(clippy::too_many_arguments)]
    fn provision_contract_user_group_uref(
        &mut self,
        package_ptr: u32,
        package_size: u32,
        label_ptr: u32,
        label_size: u32,
        output_size_ptr: u32,
    ) -> Result<Result<(), ApiError>, Error> {
        let contract_package_hash = self.t_from_mem(package_ptr, package_size)?;
        let label: String = self.t_from_mem(label_ptr, label_size)?;
        let mut contract_package = self
            .context
            .get_validated_contract_package(contract_package_hash)?;
        let groups = contract_package.groups_mut();

        let group_label = Group::new(label);

        // Ensure there are not too many urefs
        let total_urefs: usize = groups.values().map(|urefs| urefs.len()).sum();

        if total_urefs + 1 > contracts::MAX_TOTAL_UREFS {
            return Ok(Err(contracts::Error::MaxTotalURefsExceeded.into()));
        }

        // Ensure given group exists and does not exceed limits
        let group = match groups.get_mut(&group_label) {
            Some(group) if group.len() + 1 > contracts::MAX_GROUPS as usize => {
                // Ensures there are not too many groups to fit in amount of new urefs
                return Ok(Err(contracts::Error::MaxTotalURefsExceeded.into()));
            }
            Some(group) => group,
            None => return Ok(Err(contracts::Error::GroupDoesNotExist.into())),
        };

        // Proceed with creating new URefs
        let new_uref = self.context.new_unit_uref()?;
        if !group.insert(new_uref) {
            return Ok(Err(contracts::Error::URefAlreadyExists.into()));
        }

        // check we can write to the host buffer
        if let Err(err) = self.check_host_buffer() {
            return Ok(Err(err));
        }
        // create CLValue for return value
        let new_uref_value = CLValue::from_t(new_uref)?;
        let value_size = new_uref_value.inner_bytes().len();
        // write return value to buffer
        if let Err(err) = self.write_host_buffer(new_uref_value) {
            return Ok(Err(err));
        }
        // Write return value size to output location
        let output_size_bytes = value_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self
            .try_get_memory()?
            .set(output_size_ptr, &output_size_bytes)
        {
            return Err(Error::Interpreter(error.into()));
        }

        // Write updated package to the global state
        self.context
            .metered_write_gs_unsafe(contract_package_hash, contract_package)?;

        Ok(Ok(()))
    }

    #[allow(clippy::too_many_arguments)]
    fn remove_contract_user_group_urefs(
        &mut self,
        package_ptr: u32,
        package_size: u32,
        label_ptr: u32,
        label_size: u32,
        urefs_ptr: u32,
        urefs_size: u32,
    ) -> Result<Result<(), ApiError>, Error> {
        let contract_package_hash: ContractPackageHash =
            self.t_from_mem(package_ptr, package_size)?;
        let label: String = self.t_from_mem(label_ptr, label_size)?;
        let urefs: BTreeSet<URef> = self.t_from_mem(urefs_ptr, urefs_size)?;

        let mut contract_package = self
            .context
            .get_validated_contract_package(contract_package_hash)?;

        let groups = contract_package.groups_mut();
        let group_label = Group::new(label);

        let group = match groups.get_mut(&group_label) {
            Some(group) => group,
            None => return Ok(Err(contracts::Error::GroupDoesNotExist.into())),
        };

        if urefs.is_empty() {
            return Ok(Ok(()));
        }

        for uref in urefs {
            if !group.remove(&uref) {
                return Ok(Err(contracts::Error::UnableToRemoveURef.into()));
            }
        }
        // Write updated package to the global state
        self.context
            .metered_write_gs_unsafe(contract_package_hash, contract_package)?;

        Ok(Ok(()))
    }

    /// Calculate gas cost for a host function
    fn charge_host_function_call<T>(
        &mut self,
        host_function: &HostFunction<T>,
        weights: T,
    ) -> Result<(), Trap>
    where
        T: AsRef<[Cost]> + Copy,
    {
        let cost = host_function.calculate_gas_cost(weights);
        self.gas(cost)?;
        Ok(())
    }

    /// Creates a dictionary
    fn new_dictionary(&mut self, output_size_ptr: u32) -> Result<Result<(), ApiError>, Error> {
        // check we can write to the host buffer
        if let Err(err) = self.check_host_buffer() {
            return Ok(Err(err));
        }

        // Create new URef
        let new_uref = self.context.new_unit_uref()?;

        // create CLValue for return value
        let new_uref_value = CLValue::from_t(new_uref)?;
        let value_size = new_uref_value.inner_bytes().len();
        // write return value to buffer
        if let Err(err) = self.write_host_buffer(new_uref_value) {
            return Ok(Err(err));
        }
        // Write return value size to output location
        let output_size_bytes = value_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self
            .try_get_memory()?
            .set(output_size_ptr, &output_size_bytes)
        {
            return Err(Error::Interpreter(error.into()));
        }

        Ok(Ok(()))
    }

    /// Reads the `value` under a `key` in a dictionary
    fn dictionary_get(
        &mut self,
        uref_ptr: u32,
        uref_size: u32,
        dictionary_item_key_bytes_ptr: u32,
        dictionary_item_key_bytes_size: u32,
        output_size_ptr: u32,
    ) -> Result<Result<(), ApiError>, Trap> {
        // check we can write to the host buffer
        if let Err(err) = self.check_host_buffer() {
            return Ok(Err(err));
        }

        let uref: URef = self.t_from_mem(uref_ptr, uref_size)?;
        let dictionary_item_key_bytes = self.bytes_from_mem(
            dictionary_item_key_bytes_ptr,
            dictionary_item_key_bytes_size as usize,
        )?;

        let dictionary_item_key = if let Ok(item_key) = String::from_utf8(dictionary_item_key_bytes)
        {
            item_key
        } else {
            return Ok(Err(ApiError::InvalidDictionaryItemKey));
        };

        let cl_value = match self.context.dictionary_get(uref, &dictionary_item_key)? {
            Some(cl_value) => cl_value,
            None => return Ok(Err(ApiError::ValueNotFound)),
        };

        let value_size = cl_value.inner_bytes().len() as u32;
        if let Err(error) = self.write_host_buffer(cl_value) {
            return Ok(Err(error));
        }

        let value_bytes = value_size.to_le_bytes(); // Wasm is little-endian
        if let Err(error) = self.try_get_memory()?.set(output_size_ptr, &value_bytes) {
            return Err(Error::Interpreter(error.into()).into());
        }

        Ok(Ok(()))
    }

    /// Writes a `key`, `value` pair in a dictionary
    fn dictionary_put(
        &mut self,
        uref_ptr: u32,
        uref_size: u32,
        key_ptr: u32,
        key_size: u32,
        value_ptr: u32,
        value_size: u32,
    ) -> Result<Result<(), ApiError>, Trap> {
        let uref: URef = self.t_from_mem(uref_ptr, uref_size)?;
        let dictionary_item_key_bytes = self.bytes_from_mem(key_ptr, key_size as usize)?;
        if dictionary_item_key_bytes.len() > DICTIONARY_ITEM_KEY_MAX_LENGTH {
            return Ok(Err(ApiError::DictionaryItemKeyExceedsLength));
        }
        let dictionary_item_key = if let Ok(item_key) = String::from_utf8(dictionary_item_key_bytes)
        {
            item_key
        } else {
            return Ok(Err(ApiError::InvalidDictionaryItemKey));
        };
        let cl_value = self.cl_value_from_mem(value_ptr, value_size)?;
        if let Err(e) = self
            .context
            .dictionary_put(uref, &dictionary_item_key, cl_value)
        {
            return Err(Trap::from(e));
        }
        Ok(Ok(()))
    }

    /// Checks if immediate caller is a system contract or account.
    ///
    /// For cases where call stack is only the session code, then this method returns `true` if the
    /// caller is system, or `false` otherwise.
    fn is_system_immediate_caller(&self) -> Result<bool, Error> {
        let immediate_caller = match self.get_immediate_caller() {
            Some(call_stack_element) => call_stack_element,
            None => {
                // Immediate caller is assumed to exist at a time this check is run.
                return Ok(false);
            }
        };

        match immediate_caller {
            CallStackElement::Session { account_hash } => {
                // This case can happen during genesis where we're setting up purses for accounts.
                Ok(account_hash == &PublicKey::System.to_account_hash())
            }
            CallStackElement::StoredSession { contract_hash, .. }
            | CallStackElement::StoredContract { contract_hash, .. } => {
                Ok(self.context.is_system_contract(contract_hash)?)
            }
        }
    }
}