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

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! This module provides a means for executing contracts
//! represented in wasm.

mod prepare;
mod runtime;

#[cfg(doc)]
pub use crate::wasm::runtime::api_doc;

#[cfg(test)]
pub use tests::MockExt;

pub use crate::wasm::runtime::{
	AllowDeprecatedInterface, AllowUnstableInterface, CallFlags, Environment, ReturnCode, Runtime,
	RuntimeCosts,
};

use crate::{
	exec::{ExecResult, Executable, ExportedFunction, Ext},
	gas::{GasMeter, Token},
	wasm::prepare::LoadedModule,
	weights::WeightInfo,
	AccountIdOf, BadOrigin, BalanceOf, CodeHash, CodeInfoOf, CodeVec, Config, Error, Event,
	HoldReason, Pallet, PristineCode, Schedule, Weight, LOG_TARGET,
};
use codec::{Decode, Encode, MaxEncodedLen};
use frame_support::{
	dispatch::{DispatchError, DispatchResult},
	ensure,
	traits::{fungible::MutateHold, tokens::Precision::BestEffort},
};
use sp_core::Get;
use sp_runtime::RuntimeDebug;
use sp_std::prelude::*;
use wasmi::{Instance, Linker, Memory, MemoryType, StackLimits, Store};

const BYTES_PER_PAGE: usize = 64 * 1024;

/// Validated Wasm module ready for execution.
/// This data structure is immutable once created and stored.
#[derive(Encode, Decode, scale_info::TypeInfo)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct WasmBlob<T: Config> {
	code: CodeVec<T>,
	// This isn't needed for contract execution and is not stored alongside it.
	#[codec(skip)]
	code_info: CodeInfo<T>,
	// This is for not calculating the hash every time we need it.
	#[codec(skip)]
	code_hash: CodeHash<T>,
}

/// Contract code related data, such as:
///
/// - owner of the contract, i.e. account uploaded its code,
/// - storage deposit amount,
/// - reference count,
/// - determinism marker.
///
/// It is stored in a separate storage entry to avoid loading the code when not necessary.
#[derive(Clone, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)]
#[codec(mel_bound())]
#[scale_info(skip_type_params(T))]
pub struct CodeInfo<T: Config> {
	/// The account that has uploaded the contract code and hence is allowed to remove it.
	owner: AccountIdOf<T>,
	/// The amount of balance that was deposited by the owner in order to store it on-chain.
	#[codec(compact)]
	deposit: BalanceOf<T>,
	/// The number of instantiated contracts that use this as their code.
	#[codec(compact)]
	refcount: u64,
	/// Marks if the code might contain non-deterministic features and is therefore never allowed
	/// to be run on-chain. Specifically, such a code can never be instantiated into a contract
	/// and can just be used through a delegate call.
	determinism: Determinism,
	/// length of the code in bytes.
	code_len: u32,
}

/// Defines the required determinism level of a wasm blob when either running or uploading code.
#[derive(
	Clone, Copy, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen, RuntimeDebug, PartialEq, Eq,
)]
pub enum Determinism {
	/// The execution should be deterministic and hence no indeterministic instructions are
	/// allowed.
	///
	/// Dispatchables always use this mode in order to make on-chain execution deterministic.
	Enforced,
	/// Allow calling or uploading an indeterministic code.
	///
	/// This is only possible when calling into `pallet-contracts` directly via
	/// [`crate::Pallet::bare_call`].
	///
	/// # Note
	///
	/// **Never** use this mode for on-chain execution.
	Relaxed,
}

impl ExportedFunction {
	/// The wasm export name for the function.
	fn identifier(&self) -> &str {
		match self {
			Self::Constructor => "deploy",
			Self::Call => "call",
		}
	}
}

/// Cost of code loading from storage.
#[cfg_attr(test, derive(Debug, PartialEq, Eq))]
#[derive(Clone, Copy)]
struct CodeLoadToken(u32);

impl<T: Config> Token<T> for CodeLoadToken {
	fn weight(&self) -> Weight {
		// When loading the contract, we already covered the general costs of
		// calling the storage but still need to account for the actual size of the
		// contract code. This is why we subtract `T::*::(0)`. We need to do this at this
		// point because when charging the general weight for calling the contract we don't know the
		// size of the contract.
		T::WeightInfo::call_with_code_per_byte(self.0)
			.saturating_sub(T::WeightInfo::call_with_code_per_byte(0))
	}
}

impl<T: Config> WasmBlob<T> {
	/// Create the module by checking the `code`.
	pub fn from_code(
		code: Vec<u8>,
		schedule: &Schedule<T>,
		owner: AccountIdOf<T>,
		determinism: Determinism,
	) -> Result<Self, (DispatchError, &'static str)> {
		prepare::prepare::<runtime::Env, T>(
			code.try_into().map_err(|_| (<Error<T>>::CodeTooLarge.into(), ""))?,
			schedule,
			owner,
			determinism,
		)
	}

	/// Remove the code from storage and refund the deposit to its owner.
	///
	/// Applies all necessary checks before removing the code.
	pub fn remove(origin: &T::AccountId, code_hash: CodeHash<T>) -> DispatchResult {
		Self::try_remove_code(origin, code_hash)
	}

	/// Creates and returns an instance of the supplied code.
	///
	/// This is either used for later executing a contract or for validation of a contract.
	/// When validating we pass `()` as `host_state`. Please note that such a dummy instance must
	/// **never** be called/executed, since it will panic the executor.
	pub fn instantiate<E, H>(
		code: &[u8],
		host_state: H,
		schedule: &Schedule<T>,
		determinism: Determinism,
		stack_limits: StackLimits,
		allow_deprecated: AllowDeprecatedInterface,
	) -> Result<(Store<H>, Memory, Instance), &'static str>
	where
		E: Environment<H>,
	{
		let contract = LoadedModule::new::<T>(&code, determinism, Some(stack_limits))?;
		let mut store = Store::new(&contract.engine, host_state);
		let mut linker = Linker::new(&contract.engine);
		E::define(
			&mut store,
			&mut linker,
			if T::UnsafeUnstableInterface::get() {
				AllowUnstableInterface::Yes
			} else {
				AllowUnstableInterface::No
			},
			allow_deprecated,
		)
		.map_err(|_| "can't define host functions to Linker")?;

		// Query wasmi for memory limits specified in the module's import entry.
		let memory_limits = contract.scan_imports::<T>(schedule)?;
		// Here we allocate this memory in the _store_. It allocates _inital_ value, but allows it
		// to grow up to maximum number of memory pages, if necessary.
		let qed = "We checked the limits versus our Schedule,
					 which specifies the max amount of memory pages
					 well below u16::MAX; qed";
		let memory = Memory::new(
			&mut store,
			MemoryType::new(memory_limits.0, Some(memory_limits.1)).expect(qed),
		)
		.expect(qed);

		linker
			.define("env", "memory", memory)
			.expect("We just created the Linker. It has no definitions with this name; qed");

		let instance = linker
			.instantiate(&mut store, &contract.module)
			.map_err(|_| "can't instantiate module with provided definitions")?
			.ensure_no_start(&mut store)
			.map_err(|_| "start function is forbidden but found in the module")?;

		Ok((store, memory, instance))
	}

	/// Puts the module blob into storage, and returns the deposit collected for the storage.
	pub fn store_code(&mut self) -> Result<BalanceOf<T>, Error<T>> {
		let code_hash = *self.code_hash();
		<CodeInfoOf<T>>::mutate(code_hash, |stored_code_info| {
			match stored_code_info {
				// Contract code is already stored in storage. Nothing to be done here.
				Some(_) => Ok(Default::default()),
				// Upload a new contract code.
				// We need to store the code and its code_info, and collect the deposit.
				// This `None` case happens only with freshly uploaded modules. This means that
				// the `owner` is always the origin of the current transaction.
				None => {
					let deposit = self.code_info.deposit;
					T::Currency::hold(
						&HoldReason::CodeUploadDepositReserve.into(),
						&self.code_info.owner,
						deposit,
					)
					.map_err(|_| <Error<T>>::StorageDepositNotEnoughFunds)?;

					self.code_info.refcount = 0;
					<PristineCode<T>>::insert(code_hash, &self.code);
					*stored_code_info = Some(self.code_info.clone());
					<Pallet<T>>::deposit_event(
						vec![code_hash],
						Event::CodeStored {
							code_hash,
							deposit_held: deposit,
							uploader: self.code_info.owner.clone(),
						},
					);
					Ok(deposit)
				},
			}
		})
	}

	/// Try to remove code together with all associated information.
	fn try_remove_code(origin: &T::AccountId, code_hash: CodeHash<T>) -> DispatchResult {
		<CodeInfoOf<T>>::try_mutate_exists(&code_hash, |existing| {
			if let Some(code_info) = existing {
				ensure!(code_info.refcount == 0, <Error<T>>::CodeInUse);
				ensure!(&code_info.owner == origin, BadOrigin);
				let _ = T::Currency::release(
					&HoldReason::CodeUploadDepositReserve.into(),
					&code_info.owner,
					code_info.deposit,
					BestEffort,
				);
				let deposit_released = code_info.deposit;
				let remover = code_info.owner.clone();

				*existing = None;
				<PristineCode<T>>::remove(&code_hash);
				<Pallet<T>>::deposit_event(
					vec![code_hash],
					Event::CodeRemoved { code_hash, deposit_released, remover },
				);
				Ok(())
			} else {
				Err(<Error<T>>::CodeNotFound.into())
			}
		})
	}

	/// Load code with the given code hash.
	fn load_code(
		code_hash: CodeHash<T>,
		gas_meter: &mut GasMeter<T>,
	) -> Result<(CodeVec<T>, CodeInfo<T>), DispatchError> {
		let code_info = <CodeInfoOf<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
		gas_meter.charge(CodeLoadToken(code_info.code_len))?;
		let code = <PristineCode<T>>::get(code_hash).ok_or(Error::<T>::CodeNotFound)?;
		Ok((code, code_info))
	}

	/// Create the module without checking the passed code.
	///
	/// # Note
	///
	/// This is useful for benchmarking where we don't want validation of the module to skew
	/// our results. This also does not collect any deposit from the `owner`. Also useful
	/// during testing when we want to deploy codes that do not pass the instantiation checks.
	#[cfg(any(test, feature = "runtime-benchmarks"))]
	pub fn from_code_unchecked(
		code: Vec<u8>,
		schedule: &Schedule<T>,
		owner: T::AccountId,
	) -> Result<Self, DispatchError> {
		prepare::benchmarking::prepare(code, schedule, owner)
	}
}

impl<T: Config> CodeInfo<T> {
	/// Return the refcount of the module.
	#[cfg(test)]
	pub fn refcount(&self) -> u64 {
		self.refcount
	}

	#[cfg(test)]
	pub fn new(owner: T::AccountId) -> Self {
		CodeInfo {
			owner,
			deposit: Default::default(),
			refcount: 0,
			code_len: 0,
			determinism: Determinism::Enforced,
		}
	}

	/// Returns the deposit of the module.
	pub fn deposit(&self) -> BalanceOf<T> {
		self.deposit
	}
}

impl<T: Config> Executable<T> for WasmBlob<T> {
	fn from_storage(
		code_hash: CodeHash<T>,
		gas_meter: &mut GasMeter<T>,
	) -> Result<Self, DispatchError> {
		let (code, code_info) = Self::load_code(code_hash, gas_meter)?;
		Ok(Self { code, code_info, code_hash })
	}

	fn increment_refcount(code_hash: CodeHash<T>) -> Result<(), DispatchError> {
		<CodeInfoOf<T>>::mutate(code_hash, |existing| -> Result<(), DispatchError> {
			if let Some(info) = existing {
				info.refcount = info.refcount.saturating_add(1);
				Ok(())
			} else {
				Err(Error::<T>::CodeNotFound.into())
			}
		})
	}

	fn decrement_refcount(code_hash: CodeHash<T>) {
		<CodeInfoOf<T>>::mutate(code_hash, |existing| {
			if let Some(info) = existing {
				info.refcount = info.refcount.saturating_sub(1);
			}
		});
	}

	fn execute<E: Ext<T = T>>(
		self,
		ext: &mut E,
		function: &ExportedFunction,
		input_data: Vec<u8>,
	) -> ExecResult {
		let code = self.code.as_slice();
		// Instantiate the Wasm module to the engine.
		let runtime = Runtime::new(ext, input_data);
		let schedule = <T>::Schedule::get();
		let (mut store, memory, instance) = Self::instantiate::<crate::wasm::runtime::Env, _>(
			code,
			runtime,
			&schedule,
			self.code_info.determinism,
			StackLimits::default(),
			match function {
				ExportedFunction::Call => AllowDeprecatedInterface::Yes,
				ExportedFunction::Constructor => AllowDeprecatedInterface::No,
			},
		)
		.map_err(|msg| {
			log::debug!(target: LOG_TARGET, "failed to instantiate code to wasmi: {}", msg);
			Error::<T>::CodeRejected
		})?;
		store.data_mut().set_memory(memory);

		// Set fuel limit for the wasmi execution.
		// We normalize it by the base instruction weight, as its cost in wasmi engine is `1`.
		let fuel_limit = store
			.data_mut()
			.ext()
			.gas_meter_mut()
			.gas_left()
			.ref_time()
			.checked_div(T::Schedule::get().instruction_weights.base as u64)
			.ok_or(Error::<T>::InvalidSchedule)?;
		store
			.add_fuel(fuel_limit)
			.expect("We've set up engine to fuel consuming mode; qed");

		let exported_func = instance
			.get_export(&store, function.identifier())
			.and_then(|export| export.into_func())
			.ok_or_else(|| {
				log::error!(target: LOG_TARGET, "failed to find entry point");
				Error::<T>::CodeRejected
			})?;

		if let &ExportedFunction::Constructor = function {
			WasmBlob::<T>::increment_refcount(self.code_hash)?;
		}

		let result = exported_func.call(&mut store, &[], &mut []);
		let engine_consumed_total = store.fuel_consumed().expect("Fuel metering is enabled; qed");
		// Sync this frame's gas meter with the engine's one.
		let gas_meter = store.data_mut().ext().gas_meter_mut();
		gas_meter.charge_fuel(engine_consumed_total)?;

		store.into_data().to_execution_result(result)
	}

	fn code_hash(&self) -> &CodeHash<T> {
		&self.code_hash
	}

	fn code_info(&self) -> &CodeInfo<T> {
		&self.code_info
	}

	fn code_len(&self) -> u32 {
		self.code.len() as u32
	}

	fn is_deterministic(&self) -> bool {
		matches!(self.code_info.determinism, Determinism::Enforced)
	}
}

#[cfg(test)]
mod tests {
	use super::*;
	use crate::{
		exec::{AccountIdOf, ErrorOrigin, ExecError, Executable, Ext, Key, SeedOf},
		gas::GasMeter,
		storage::WriteOutcome,
		tests::{RuntimeCall, Test, ALICE, BOB},
		BalanceOf, CodeHash, Error, Origin, Pallet as Contracts,
	};
	use assert_matches::assert_matches;
	use frame_support::{
		assert_err, assert_ok, dispatch::DispatchResultWithPostInfo, weights::Weight,
	};
	use frame_system::pallet_prelude::BlockNumberFor;
	use pallet_contracts_primitives::{ExecReturnValue, ReturnFlags};
	use pretty_assertions::assert_eq;
	use sp_core::H256;
	use sp_runtime::DispatchError;
	use std::{
		borrow::BorrowMut,
		cell::RefCell,
		collections::{
			hash_map::{Entry, HashMap},
			HashSet,
		},
	};

	#[derive(Debug, PartialEq, Eq)]
	struct InstantiateEntry {
		code_hash: H256,
		value: u64,
		data: Vec<u8>,
		gas_left: u64,
		salt: Vec<u8>,
	}

	#[derive(Debug, PartialEq, Eq)]
	struct TerminationEntry {
		beneficiary: AccountIdOf<Test>,
	}

	#[derive(Debug, PartialEq, Eq)]
	struct TransferEntry {
		to: AccountIdOf<Test>,
		value: u64,
	}

	#[derive(Debug, PartialEq, Eq)]
	struct CallEntry {
		to: AccountIdOf<Test>,
		value: u64,
		data: Vec<u8>,
		allows_reentry: bool,
	}

	#[derive(Debug, PartialEq, Eq)]
	struct CallCodeEntry {
		code_hash: H256,
		data: Vec<u8>,
	}

	pub struct MockExt {
		storage: HashMap<Vec<u8>, Vec<u8>>,
		instantiates: Vec<InstantiateEntry>,
		terminations: Vec<TerminationEntry>,
		calls: Vec<CallEntry>,
		code_calls: Vec<CallCodeEntry>,
		transfers: Vec<TransferEntry>,
		// (topics, data)
		events: Vec<(Vec<H256>, Vec<u8>)>,
		runtime_calls: RefCell<Vec<RuntimeCall>>,
		schedule: Schedule<Test>,
		gas_meter: GasMeter<Test>,
		debug_buffer: Vec<u8>,
		ecdsa_recover: RefCell<Vec<([u8; 65], [u8; 32])>>,
		sr25519_verify: RefCell<Vec<([u8; 64], Vec<u8>, [u8; 32])>>,
		code_hashes: Vec<CodeHash<Test>>,
		caller: Origin<Test>,
		delegate_dependencies: RefCell<HashSet<CodeHash<Test>>>,
	}

	/// The call is mocked and just returns this hardcoded value.
	fn call_return_data() -> Vec<u8> {
		vec![0xDE, 0xAD, 0xBE, 0xEF]
	}

	impl Default for MockExt {
		fn default() -> Self {
			Self {
				code_hashes: Default::default(),
				storage: Default::default(),
				instantiates: Default::default(),
				terminations: Default::default(),
				calls: Default::default(),
				code_calls: Default::default(),
				transfers: Default::default(),
				events: Default::default(),
				runtime_calls: Default::default(),
				schedule: Default::default(),
				gas_meter: GasMeter::new(Weight::from_parts(10_000_000_000, 10 * 1024 * 1024)),
				debug_buffer: Default::default(),
				ecdsa_recover: Default::default(),
				caller: Default::default(),
				sr25519_verify: Default::default(),
				delegate_dependencies: Default::default(),
			}
		}
	}

	impl Ext for MockExt {
		type T = Test;

		fn call(
			&mut self,
			_gas_limit: Weight,
			_deposit_limit: BalanceOf<Self::T>,
			to: AccountIdOf<Self::T>,
			value: u64,
			data: Vec<u8>,
			allows_reentry: bool,
		) -> Result<ExecReturnValue, ExecError> {
			self.calls.push(CallEntry { to, value, data, allows_reentry });
			Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() })
		}
		fn delegate_call(
			&mut self,
			code_hash: CodeHash<Self::T>,
			data: Vec<u8>,
		) -> Result<ExecReturnValue, ExecError> {
			self.code_calls.push(CallCodeEntry { code_hash, data });
			Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: call_return_data() })
		}
		fn instantiate(
			&mut self,
			gas_limit: Weight,
			_deposit_limit: BalanceOf<Self::T>,
			code_hash: CodeHash<Test>,
			value: u64,
			data: Vec<u8>,
			salt: &[u8],
		) -> Result<(AccountIdOf<Self::T>, ExecReturnValue), ExecError> {
			self.instantiates.push(InstantiateEntry {
				code_hash,
				value,
				data: data.to_vec(),
				gas_left: gas_limit.ref_time(),
				salt: salt.to_vec(),
			});
			Ok((
				Contracts::<Test>::contract_address(&ALICE, &code_hash, &data, salt),
				ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() },
			))
		}
		fn set_code_hash(&mut self, hash: CodeHash<Self::T>) -> Result<(), DispatchError> {
			self.code_hashes.push(hash);
			Ok(())
		}
		fn transfer(&mut self, to: &AccountIdOf<Self::T>, value: u64) -> Result<(), DispatchError> {
			self.transfers.push(TransferEntry { to: to.clone(), value });
			Ok(())
		}
		fn terminate(&mut self, beneficiary: &AccountIdOf<Self::T>) -> Result<(), DispatchError> {
			self.terminations.push(TerminationEntry { beneficiary: beneficiary.clone() });
			Ok(())
		}
		fn get_storage(&mut self, key: &Key<Self::T>) -> Option<Vec<u8>> {
			self.storage.get(&key.to_vec()).cloned()
		}
		fn get_storage_size(&mut self, key: &Key<Self::T>) -> Option<u32> {
			self.storage.get(&key.to_vec()).map(|val| val.len() as u32)
		}
		fn set_storage(
			&mut self,
			key: &Key<Self::T>,
			value: Option<Vec<u8>>,
			take_old: bool,
		) -> Result<WriteOutcome, DispatchError> {
			let key = key.to_vec();
			let entry = self.storage.entry(key.clone());
			let result = match (entry, take_old) {
				(Entry::Vacant(_), _) => WriteOutcome::New,
				(Entry::Occupied(entry), false) =>
					WriteOutcome::Overwritten(entry.remove().len() as u32),
				(Entry::Occupied(entry), true) => WriteOutcome::Taken(entry.remove()),
			};
			if let Some(value) = value {
				self.storage.insert(key, value);
			}
			Ok(result)
		}
		fn caller(&self) -> Origin<Self::T> {
			self.caller.clone()
		}
		fn is_contract(&self, _address: &AccountIdOf<Self::T>) -> bool {
			true
		}
		fn code_hash(&self, _address: &AccountIdOf<Self::T>) -> Option<CodeHash<Self::T>> {
			Some(H256::from_slice(&[0x11; 32]))
		}
		fn own_code_hash(&mut self) -> &CodeHash<Self::T> {
			const HASH: H256 = H256::repeat_byte(0x10);
			&HASH
		}
		fn caller_is_origin(&self) -> bool {
			false
		}
		fn caller_is_root(&self) -> bool {
			&self.caller == &Origin::Root
		}
		fn address(&self) -> &AccountIdOf<Self::T> {
			&BOB
		}
		fn balance(&self) -> u64 {
			228
		}
		fn value_transferred(&self) -> u64 {
			1337
		}
		fn now(&self) -> &u64 {
			&1111
		}
		fn minimum_balance(&self) -> u64 {
			666
		}
		fn random(&self, subject: &[u8]) -> (SeedOf<Self::T>, BlockNumberFor<Self::T>) {
			(H256::from_slice(subject), 42)
		}
		fn deposit_event(&mut self, topics: Vec<H256>, data: Vec<u8>) {
			self.events.push((topics, data))
		}
		fn block_number(&self) -> u64 {
			121
		}
		fn max_value_size(&self) -> u32 {
			16_384
		}
		fn get_weight_price(&self, weight: Weight) -> BalanceOf<Self::T> {
			BalanceOf::<Self::T>::from(1312_u32)
				.saturating_mul(weight.ref_time().into())
				.saturating_add(
					BalanceOf::<Self::T>::from(103_u32).saturating_mul(weight.proof_size()),
				)
		}
		fn schedule(&self) -> &Schedule<Self::T> {
			&self.schedule
		}
		fn gas_meter(&self) -> &GasMeter<Self::T> {
			&self.gas_meter
		}
		fn gas_meter_mut(&mut self) -> &mut GasMeter<Self::T> {
			&mut self.gas_meter
		}
		fn charge_storage(&mut self, _diff: &crate::storage::meter::Diff) {}
		fn append_debug_buffer(&mut self, msg: &str) -> bool {
			self.debug_buffer.extend(msg.as_bytes());
			true
		}
		fn call_runtime(
			&self,
			call: <Self::T as Config>::RuntimeCall,
		) -> DispatchResultWithPostInfo {
			self.runtime_calls.borrow_mut().push(call);
			Ok(Default::default())
		}
		fn ecdsa_recover(
			&self,
			signature: &[u8; 65],
			message_hash: &[u8; 32],
		) -> Result<[u8; 33], ()> {
			self.ecdsa_recover.borrow_mut().push((*signature, *message_hash));
			Ok([3; 33])
		}
		fn sr25519_verify(&self, signature: &[u8; 64], message: &[u8], pub_key: &[u8; 32]) -> bool {
			self.sr25519_verify.borrow_mut().push((*signature, message.to_vec(), *pub_key));
			true
		}
		fn contract_info(&mut self) -> &mut crate::ContractInfo<Self::T> {
			unimplemented!()
		}
		fn ecdsa_to_eth_address(&self, _pk: &[u8; 33]) -> Result<[u8; 20], ()> {
			Ok([2u8; 20])
		}
		fn reentrance_count(&self) -> u32 {
			12
		}
		fn account_reentrance_count(&self, _account_id: &AccountIdOf<Self::T>) -> u32 {
			12
		}
		fn nonce(&mut self) -> u64 {
			995
		}

		fn add_delegate_dependency(
			&mut self,
			code: CodeHash<Self::T>,
		) -> Result<(), DispatchError> {
			self.delegate_dependencies.borrow_mut().insert(code);
			Ok(())
		}

		fn remove_delegate_dependency(
			&mut self,
			code: &CodeHash<Self::T>,
		) -> Result<(), DispatchError> {
			self.delegate_dependencies.borrow_mut().remove(code);
			Ok(())
		}
	}

	/// Execute the supplied code.
	///
	/// Not used directly but through the wrapper functions defined below.
	fn execute_internal<E: BorrowMut<MockExt>>(
		wat: &str,
		input_data: Vec<u8>,
		mut ext: E,
		entry_point: &ExportedFunction,
		unstable_interface: bool,
		skip_checks: bool,
	) -> ExecResult {
		type RuntimeConfig = <MockExt as Ext>::T;
		RuntimeConfig::set_unstable_interface(unstable_interface);
		let wasm = wat::parse_str(wat).unwrap();
		let executable = if skip_checks {
			WasmBlob::<RuntimeConfig>::from_code_unchecked(
				wasm,
				ext.borrow_mut().schedule(),
				ALICE,
			)?
		} else {
			WasmBlob::<RuntimeConfig>::from_code(
				wasm,
				ext.borrow_mut().schedule(),
				ALICE,
				Determinism::Enforced,
			)
			.map_err(|err| err.0)?
		};
		executable.execute(ext.borrow_mut(), entry_point, input_data)
	}

	/// Execute the supplied code.
	fn execute<E: BorrowMut<MockExt>>(wat: &str, input_data: Vec<u8>, ext: E) -> ExecResult {
		execute_internal(wat, input_data, ext, &ExportedFunction::Call, true, false)
	}

	/// Execute the supplied code with disabled unstable functions.
	///
	/// In our test config unstable functions are disabled so that we can test them.
	/// In order to test that code using them is properly rejected we temporarily disable
	/// them when this test is run.
	#[cfg(not(feature = "runtime-benchmarks"))]
	fn execute_no_unstable<E: BorrowMut<MockExt>>(
		wat: &str,
		input_data: Vec<u8>,
		ext: E,
	) -> ExecResult {
		execute_internal(wat, input_data, ext, &ExportedFunction::Call, false, false)
	}

	/// Execute code without validating it first.
	///
	/// This is mainly useful in order to test code which uses deprecated functions. Those
	/// would fail when validating the code.
	fn execute_unvalidated<E: BorrowMut<MockExt>>(
		wat: &str,
		input_data: Vec<u8>,
		ext: E,
	) -> ExecResult {
		execute_internal(wat, input_data, ext, &ExportedFunction::Call, false, true)
	}

	/// Execute instantiation entry point of code without validating it first.
	///
	/// Same as `execute_unvalidated` except that the `deploy` entry point is ran.
	#[cfg(not(feature = "runtime-benchmarks"))]
	fn execute_instantiate_unvalidated<E: BorrowMut<MockExt>>(
		wat: &str,
		input_data: Vec<u8>,
		ext: E,
	) -> ExecResult {
		execute_internal(wat, input_data, ext, &ExportedFunction::Constructor, false, true)
	}

	const CODE_TRANSFER: &str = r#"
(module
	;; seal_transfer(
	;;    account_ptr: u32,
	;;    account_len: u32,
	;;    value_ptr: u32,
	;;    value_len: u32,
	;;) -> u32
	(import "seal0" "seal_transfer" (func $seal_transfer (param i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_transfer
				(i32.const 4)  ;; Pointer to "account" address.
				(i32.const 32)  ;; Length of "account" address.
				(i32.const 36) ;; Pointer to the buffer with value to transfer
				(i32.const 8)  ;; Length of the buffer with value to transfer.
			)
		)
	)
	(func (export "deploy"))

	;; Destination AccountId (ALICE)
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;; Amount of value to transfer.
	;; Represented by u64 (8 bytes long) in little endian.
	(data (i32.const 36) "\99\00\00\00\00\00\00\00")
)
"#;

	#[test]
	fn contract_transfer() {
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(CODE_TRANSFER, vec![], &mut mock_ext));

		assert_eq!(&mock_ext.transfers, &[TransferEntry { to: ALICE, value: 153 }]);
	}

	const CODE_CALL: &str = r#"
(module
	;; seal_call(
	;;    callee_ptr: u32,
	;;    callee_len: u32,
	;;    gas: u64,
	;;    value_ptr: u32,
	;;    value_len: u32,
	;;    input_data_ptr: u32,
	;;    input_data_len: u32,
	;;    output_ptr: u32,
	;;    output_len_ptr: u32
	;;) -> u32
	(import "seal0" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_call
				(i32.const 4)  ;; Pointer to "callee" address.
				(i32.const 32)  ;; Length of "callee" address.
				(i64.const 0)  ;; How much gas to devote for the execution. 0 = all.
				(i32.const 36) ;; Pointer to the buffer with value to transfer
				(i32.const 8)  ;; Length of the buffer with value to transfer.
				(i32.const 44) ;; Pointer to input data buffer address
				(i32.const 4)  ;; Length of input data buffer
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
				(i32.const 0) ;; Length is ignored in this case
			)
		)
	)
	(func (export "deploy"))

	;; Destination AccountId (ALICE)
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;; Amount of value to transfer.
	;; Represented by u64 (8 bytes long) in little endian.
	(data (i32.const 36) "\06\00\00\00\00\00\00\00")

	(data (i32.const 44) "\01\02\03\04")
)
"#;

	#[test]
	fn contract_call() {
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(CODE_CALL, vec![], &mut mock_ext));

		assert_eq!(
			&mock_ext.calls,
			&[CallEntry { to: ALICE, value: 6, data: vec![1, 2, 3, 4], allows_reentry: true }]
		);
	}

	#[test]
	fn contract_delegate_call() {
		const CODE: &str = r#"
(module
	;; seal_delegate_call(
	;;    flags: u32,
	;;    code_hash_ptr: u32,
	;;    input_data_ptr: u32,
	;;    input_data_len: u32,
	;;    output_ptr: u32,
	;;    output_len_ptr: u32
	;;) -> u32
	(import "seal0" "seal_delegate_call" (func $seal_delegate_call (param i32 i32 i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_delegate_call
				(i32.const 0) ;; No flags are set
				(i32.const 4)  ;; Pointer to "callee" code_hash.
				(i32.const 36) ;; Pointer to input data buffer address
				(i32.const 4)  ;; Length of input data buffer
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
				(i32.const 0) ;; Length is ignored in this case
			)
		)
	)
	(func (export "deploy"))

	;; Callee code_hash
	(data (i32.const 4)
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
	)

	(data (i32.const 36) "\01\02\03\04")
)
"#;
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(CODE, vec![], &mut mock_ext));

		assert_eq!(
			&mock_ext.code_calls,
			&[CallCodeEntry { code_hash: [0x11; 32].into(), data: vec![1, 2, 3, 4] }]
		);
	}

	#[test]
	fn contract_call_forward_input() {
		const CODE: &str = r#"
(module
	(import "seal1" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32) (result i32)))
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_call
				(i32.const 1) ;; Set FORWARD_INPUT bit
				(i32.const 4)  ;; Pointer to "callee" address.
				(i64.const 0)  ;; How much gas to devote for the execution. 0 = all.
				(i32.const 36) ;; Pointer to the buffer with value to transfer
				(i32.const 44) ;; Pointer to input data buffer address
				(i32.const 4)  ;; Length of input data buffer
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
				(i32.const 0) ;; Length is ignored in this case
			)
		)

		;; triggers a trap because we already forwarded the input
		(call $seal_input (i32.const 1) (i32.const 44))
	)

	(func (export "deploy"))

	;; Destination AccountId (ALICE)
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;; Amount of value to transfer.
	;; Represented by u64 (8 bytes long) in little endian.
	(data (i32.const 36) "\2A\00\00\00\00\00\00\00")

	;; The input is ignored because we forward our own input
	(data (i32.const 44) "\01\02\03\04")
)
"#;
		let mut mock_ext = MockExt::default();
		let input = vec![0xff, 0x2a, 0x99, 0x88];
		assert_err!(execute(CODE, input.clone(), &mut mock_ext), <Error<Test>>::InputForwarded,);

		assert_eq!(
			&mock_ext.calls,
			&[CallEntry { to: ALICE, value: 0x2a, data: input, allows_reentry: false }]
		);
	}

	#[test]
	fn contract_call_clone_input() {
		const CODE: &str = r#"
(module
	(import "seal1" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32) (result i32)))
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_call
				(i32.const 11) ;; Set FORWARD_INPUT | CLONE_INPUT | ALLOW_REENTRY bits
				(i32.const 4)  ;; Pointer to "callee" address.
				(i64.const 0)  ;; How much gas to devote for the execution. 0 = all.
				(i32.const 36) ;; Pointer to the buffer with value to transfer
				(i32.const 44) ;; Pointer to input data buffer address
				(i32.const 4)  ;; Length of input data buffer
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
				(i32.const 0) ;; Length is ignored in this case
			)
		)

		;; works because the input was cloned
		(call $seal_input (i32.const 0) (i32.const 44))

		;; return the input to caller for inspection
		(call $seal_return (i32.const 0) (i32.const 0) (i32.load (i32.const 44)))
	)

	(func (export "deploy"))

	;; Destination AccountId (ALICE)
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;; Amount of value to transfer.
	;; Represented by u64 (8 bytes long) in little endian.
	(data (i32.const 36) "\2A\00\00\00\00\00\00\00")

	;; The input is ignored because we forward our own input
	(data (i32.const 44) "\01\02\03\04")
)
"#;
		let mut mock_ext = MockExt::default();
		let input = vec![0xff, 0x2a, 0x99, 0x88];
		let result = execute(CODE, input.clone(), &mut mock_ext).unwrap();
		assert_eq!(result.data, input);
		assert_eq!(
			&mock_ext.calls,
			&[CallEntry { to: ALICE, value: 0x2a, data: input, allows_reentry: true }]
		);
	}

	#[test]
	fn contract_call_tail_call() {
		const CODE: &str = r#"
(module
	(import "seal1" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_call
				(i32.const 5) ;; Set FORWARD_INPUT | TAIL_CALL bit
				(i32.const 4)  ;; Pointer to "callee" address.
				(i64.const 0)  ;; How much gas to devote for the execution. 0 = all.
				(i32.const 36) ;; Pointer to the buffer with value to transfer
				(i32.const 0) ;; Pointer to input data buffer address
				(i32.const 0)  ;; Length of input data buffer
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
				(i32.const 0) ;; Length is ignored in this case
			)
		)

		;; a tail call never returns
		(unreachable)
	)

	(func (export "deploy"))

	;; Destination AccountId (ALICE)
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;; Amount of value to transfer.
	;; Represented by u64 (8 bytes long) in little endian.
	(data (i32.const 36) "\2A\00\00\00\00\00\00\00")
)
"#;
		let mut mock_ext = MockExt::default();
		let input = vec![0xff, 0x2a, 0x99, 0x88];
		let result = execute(CODE, input.clone(), &mut mock_ext).unwrap();
		assert_eq!(result.data, call_return_data());
		assert_eq!(
			&mock_ext.calls,
			&[CallEntry { to: ALICE, value: 0x2a, data: input, allows_reentry: false }]
		);
	}

	#[test]
	fn contains_storage_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal1" "contains_storage" (func $contains_storage (param i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))


	;; size of input buffer
	;; [0, 4) size of input buffer (128+32 = 160 bytes = 0xA0)
	(data (i32.const 0) "\A0")

	;; [4, 164) input buffer

	(func (export "call")
		;; Receive key
		(call $seal_input
			(i32.const 4)	;; Where we take input and store it
			(i32.const 0)	;; Where we take and store the length of the data
		)
		;; Call seal_clear_storage and save what it returns at 0
		(i32.store (i32.const 0)
			(call $contains_storage
				(i32.const 8)			;; key_ptr
				(i32.load (i32.const 4))	;; key_len
			)
		)
		(call $seal_return
			(i32.const 0)	;; flags
			(i32.const 0)	;; returned value
			(i32.const 4)	;; length of returned value
		)
	)

	(func (export "deploy"))
)
"#;

		let mut ext = MockExt::default();
		ext.set_storage(
			&Key::<Test>::try_from_var([1u8; 64].to_vec()).unwrap(),
			Some(vec![42u8]),
			false,
		)
		.unwrap();
		ext.set_storage(
			&Key::<Test>::try_from_var([2u8; 19].to_vec()).unwrap(),
			Some(vec![]),
			false,
		)
		.unwrap();

		//value does not exist (wrong key length)
		let input = (63, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		// sentinel returned
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL);

		// value exists
		let input = (64, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		// true as u32 returned
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 1);
		// getter does not remove the value from storage
		assert_eq!(ext.storage.get(&[1u8; 64].to_vec()).unwrap(), &[42u8]);

		// value exists (test for 0 sized)
		let input = (19, [2u8; 19]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		// true as u32 returned
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0);
		// getter does not remove the value from storage
		assert_eq!(ext.storage.get(&[2u8; 19].to_vec()).unwrap(), &([] as [u8; 0]));
	}

	const CODE_INSTANTIATE: &str = r#"
(module
	;; seal_instantiate(
	;;     code_ptr: u32,
	;;     code_len: u32,
	;;     gas: u64,
	;;     value_ptr: u32,
	;;     value_len: u32,
	;;     input_data_ptr: u32,
	;;     input_data_len: u32,
	;;     input_data_len: u32,
	;;     address_ptr: u32,
	;;     address_len_ptr: u32,
	;;     output_ptr: u32,
	;;     output_len_ptr: u32
	;; ) -> u32
	(import "seal0" "seal_instantiate" (func $seal_instantiate
		(param i32 i32 i64 i32 i32 i32 i32 i32 i32 i32 i32 i32 i32) (result i32)
	))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_instantiate
				(i32.const 16)   ;; Pointer to `code_hash`
				(i32.const 32)   ;; Length of `code_hash`
				(i64.const 0)    ;; How much gas to devote for the execution. 0 = all.
				(i32.const 4)    ;; Pointer to the buffer with value to transfer
				(i32.const 8)    ;; Length of the buffer with value to transfer
				(i32.const 12)   ;; Pointer to input data buffer address
				(i32.const 4)    ;; Length of input data buffer
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy address
				(i32.const 0) ;; Length is ignored in this case
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
				(i32.const 0) ;; Length is ignored in this case
				(i32.const 0) ;; salt_ptr
				(i32.const 4) ;; salt_len
			)
		)
	)
	(func (export "deploy"))

	;; Salt
	(data (i32.const 0) "\42\43\44\45")
	;; Amount of value to transfer.
	;; Represented by u64 (8 bytes long) in little endian.
	(data (i32.const 4) "\03\00\00\00\00\00\00\00")
	;; Input data to pass to the contract being instantiated.
	(data (i32.const 12) "\01\02\03\04")
	;; Hash of code.
	(data (i32.const 16)
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
	)
)
"#;

	#[test]
	fn contract_instantiate() {
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(CODE_INSTANTIATE, vec![], &mut mock_ext));

		assert_matches!(
			&mock_ext.instantiates[..],
			[InstantiateEntry {
				code_hash,
				value: 3,
				data,
				gas_left: _,
				salt,
			}] if
				code_hash == &[0x11; 32].into() &&
				data == &vec![1, 2, 3, 4] &&
				salt == &vec![0x42, 0x43, 0x44, 0x45]
		);
	}

	const CODE_TERMINATE: &str = r#"
(module
	;; seal_terminate(
	;;     beneficiary_ptr: u32,
	;;     beneficiary_len: u32,
	;; )
	(import "seal0" "seal_terminate" (func $seal_terminate (param i32 i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(call $seal_terminate
			(i32.const 4)  ;; Pointer to "beneficiary" address.
			(i32.const 32)  ;; Length of "beneficiary" address.
		)
	)
	(func (export "deploy"))

	;; Beneficiary AccountId to transfer the funds.
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)
)
"#;

	#[test]
	fn contract_terminate() {
		let mut mock_ext = MockExt::default();
		execute(CODE_TERMINATE, vec![], &mut mock_ext).unwrap();

		assert_eq!(&mock_ext.terminations, &[TerminationEntry { beneficiary: ALICE }]);
	}

	const CODE_TRANSFER_LIMITED_GAS: &str = r#"
(module
	;; seal_call(
	;;    callee_ptr: u32,
	;;    callee_len: u32,
	;;    gas: u64,
	;;    value_ptr: u32,
	;;    value_len: u32,
	;;    input_data_ptr: u32,
	;;    input_data_len: u32,
	;;    output_ptr: u32,
	;;    output_len_ptr: u32
	;;) -> u32
	(import "seal0" "seal_call" (func $seal_call (param i32 i32 i64 i32 i32 i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_call
				(i32.const 4)  ;; Pointer to "callee" address.
				(i32.const 32)  ;; Length of "callee" address.
				(i64.const 228)  ;; How much gas to devote for the execution.
				(i32.const 36)  ;; Pointer to the buffer with value to transfer
				(i32.const 8)   ;; Length of the buffer with value to transfer.
				(i32.const 44)   ;; Pointer to input data buffer address
				(i32.const 4)   ;; Length of input data buffer
				(i32.const 4294967295) ;; u32 max value is the sentinel value: do not copy output
				(i32.const 0) ;; Length is ignored in this cas
			)
		)
	)
	(func (export "deploy"))

	;; Destination AccountId to transfer the funds.
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)
	;; Amount of value to transfer.
	;; Represented by u64 (8 bytes long) in little endian.
	(data (i32.const 36) "\06\00\00\00\00\00\00\00")

	(data (i32.const 44) "\01\02\03\04")
)
"#;

	#[test]
	fn contract_call_limited_gas() {
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(&CODE_TRANSFER_LIMITED_GAS, vec![], &mut mock_ext));

		assert_eq!(
			&mock_ext.calls,
			&[CallEntry { to: ALICE, value: 6, data: vec![1, 2, 3, 4], allows_reentry: true }]
		);
	}

	const CODE_ECDSA_RECOVER: &str = r#"
(module
	;; seal_ecdsa_recover(
	;;    signature_ptr: u32,
	;;    message_hash_ptr: u32,
	;;    output_ptr: u32
	;; ) -> u32
	(import "seal0" "seal_ecdsa_recover" (func $seal_ecdsa_recover (param i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $seal_ecdsa_recover
				(i32.const 36) ;; Pointer to signature.
				(i32.const 4)  ;; Pointer to message hash.
				(i32.const 36) ;; Pointer for output - public key.
			)
		)
	)
	(func (export "deploy"))

	;; Hash of message.
	(data (i32.const 4)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)
	;; Signature
	(data (i32.const 36)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01"
	)
)
"#;

	#[test]
	fn contract_ecdsa_recover() {
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(&CODE_ECDSA_RECOVER, vec![], &mut mock_ext));
		assert_eq!(mock_ext.ecdsa_recover.into_inner(), [([1; 65], [1; 32])]);
	}

	#[test]
	fn contract_ecdsa_to_eth_address() {
		/// calls `seal_ecdsa_to_eth_address` for the contstant and ensures the result equals the
		/// expected one.
		const CODE_ECDSA_TO_ETH_ADDRESS: &str = r#"
(module
	(import "seal0" "seal_ecdsa_to_eth_address" (func $seal_ecdsa_to_eth_address (param i32 i32) (result i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call")
		;; fill the buffer with the eth address.
		(call $seal_ecdsa_to_eth_address (i32.const 0) (i32.const 0))

		;; Return the contents of the buffer
		(call $seal_return
			(i32.const 0)
			(i32.const 0)
			(i32.const 20)
		)

		;; seal_return doesn't return, so this is effectively unreachable.
		(unreachable)
	)
	(func (export "deploy"))
)
"#;

		let output = execute(CODE_ECDSA_TO_ETH_ADDRESS, vec![], MockExt::default()).unwrap();
		assert_eq!(
			output,
			ExecReturnValue { flags: ReturnFlags::empty(), data: [0x02; 20].to_vec() }
		);
	}

	#[test]
	fn contract_sr25519() {
		const CODE_SR25519: &str = r#"
(module
	(import "seal0" "sr25519_verify" (func $sr25519_verify (param i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(drop
			(call $sr25519_verify
				(i32.const 0) ;; Pointer to signature.
				(i32.const 64) ;; Pointer to public key.
				(i32.const 16) ;; message length.
				(i32.const 96) ;; Pointer to message.
			)
		)
	)
	(func (export "deploy"))

	;; Signature (64 bytes)
	(data (i32.const 0)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;;  public key (32 bytes)
	(data (i32.const 64)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;;  message. (16 bytes)
	(data (i32.const 96)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)
)
"#;
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(&CODE_SR25519, vec![], &mut mock_ext));
		assert_eq!(mock_ext.sr25519_verify.into_inner(), [([1; 64], [1; 16].to_vec(), [1; 32])]);
	}

	const CODE_GET_STORAGE: &str = r#"
(module
	(import "seal0" "seal_get_storage" (func $seal_get_storage (param i32 i32 i32) (result i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; [0, 32) key for get storage
	(data (i32.const 0)
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
	)

	;; [32, 36) buffer size = 4k in little endian
	(data (i32.const 32) "\00\10")

	;; [36; inf) buffer where the result is copied

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		(local $buf_size i32)

		;; Load a storage value into contract memory.
		(call $assert
			(i32.eq
				(call $seal_get_storage
					(i32.const 0)		;; The pointer to the storage key to fetch
					(i32.const 36)		;; Pointer to the output buffer
					(i32.const 32)		;; Pointer to the size of the buffer
				)

				;; Return value 0 means that the value is found and there were
				;; no errors.
				(i32.const 0)
			)
		)

		;; Find out the size of the buffer
		(set_local $buf_size
			(i32.load (i32.const 32))
		)

		;; Return the contents of the buffer
		(call $seal_return
			(i32.const 0)
			(i32.const 36)
			(get_local $buf_size)
		)

		;; env:seal_return doesn't return, so this is effectively unreachable.
		(unreachable)
	)

	(func (export "deploy"))
)
"#;

	#[test]
	fn get_storage_puts_data_into_buf() {
		let mut mock_ext = MockExt::default();
		mock_ext.storage.insert([0x11; 32].to_vec(), [0x22; 32].to_vec());

		let output = execute(CODE_GET_STORAGE, vec![], mock_ext).unwrap();

		assert_eq!(
			output,
			ExecReturnValue { flags: ReturnFlags::empty(), data: [0x22; 32].to_vec() }
		);
	}

	/// calls `seal_caller` and compares the result with the constant (ALICE's address part).
	const CODE_CALLER: &str = r#"
(module
	(import "seal0" "seal_caller" (func $seal_caller (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; fill the buffer with the caller.
		(call $seal_caller (i32.const 0) (i32.const 32))

		;; assert len == 32
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 32)
			)
		)

		;; assert that the first 8 bytes are the beginning of "ALICE"
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 0x0101010101010101)
			)
		)
	)

	(func (export "deploy"))
)
"#;

	#[test]
	fn caller() {
		assert_ok!(execute(CODE_CALLER, vec![], MockExt::default()));
	}

	#[test]
	fn caller_traps_when_no_account_id() {
		let mut ext = MockExt::default();
		ext.caller = Origin::Root;
		assert_eq!(
			execute(CODE_CALLER, vec![], ext),
			Err(ExecError { error: DispatchError::RootNotAllowed, origin: ErrorOrigin::Caller })
		);
	}

	/// calls `seal_address` and compares the result with the constant (BOB's address part).
	const CODE_ADDRESS: &str = r#"
(module
	(import "seal0" "seal_address" (func $seal_address (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; fill the buffer with the self address.
		(call $seal_address (i32.const 0) (i32.const 32))

		;; assert size == 32
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 32)
			)
		)

		;; assert that the first 8 bytes are the beginning of "BOB"
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 0x0202020202020202)
			)
		)
	)

	(func (export "deploy"))
)
"#;

	#[test]
	fn address() {
		assert_ok!(execute(CODE_ADDRESS, vec![], MockExt::default()));
	}

	const CODE_BALANCE: &str = r#"
(module
	(import "seal0" "seal_balance" (func $seal_balance (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the balance in the buffer
		(call $seal_balance (i32.const 0) (i32.const 32))

		;; assert len == 8
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 8)
			)
		)

		;; assert that contents of the buffer is equal to the i64 value of 228.
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 228)
			)
		)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn balance() {
		assert_ok!(execute(CODE_BALANCE, vec![], MockExt::default()));
	}

	const CODE_GAS_PRICE: &str = r#"
(module
	(import "seal1" "weight_to_fee" (func $seal_weight_to_fee (param i64 i64 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the gas price in the buffer
		(call $seal_weight_to_fee (i64.const 2) (i64.const 1) (i32.const 0) (i32.const 32))

		;; assert len == 8
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 8)
			)
		)

		;; assert that contents of the buffer is equal to the i64 value of 2 * 1312 + 103 = 2727.
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 2727)
			)
		)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn gas_price() {
		assert_ok!(execute(CODE_GAS_PRICE, vec![], MockExt::default()));
	}

	const CODE_GAS_LEFT: &str = r#"
(module
	(import "seal1" "gas_left" (func $seal_gas_left (param i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; Make output buffer size 20 bytes
	(data (i32.const 20) "\14")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the weight left to the buffer
		(call $seal_gas_left (i32.const 0) (i32.const 20))

		;; Assert len <= 16 (max encoded Weight len)
		(call $assert
			(i32.le_u
				(i32.load (i32.const 20))
				(i32.const 16)
			)
		)

		;; Return weight left and its encoded value len
		(call $seal_return (i32.const 0) (i32.const 0) (i32.load (i32.const 20)))

		(unreachable)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn gas_left() {
		let mut ext = MockExt::default();
		let gas_limit = ext.gas_meter.gas_left();

		let output = execute(CODE_GAS_LEFT, vec![], &mut ext).unwrap();

		let weight_left = Weight::decode(&mut &*output.data).unwrap();
		let actual_left = ext.gas_meter.gas_left();

		assert!(weight_left.all_lt(gas_limit), "gas_left must be less than initial");
		assert!(weight_left.all_gt(actual_left), "gas_left must be greater than final");
	}

	/// Test that [`frame_support::weights::OldWeight`] en/decodes the same as our
	/// [`crate::OldWeight`].
	#[test]
	fn old_weight_decode() {
		#![allow(deprecated)]
		let sp = frame_support::weights::OldWeight(42).encode();
		let our = crate::OldWeight::decode(&mut &*sp).unwrap();

		assert_eq!(our, 42);
	}

	const CODE_VALUE_TRANSFERRED: &str = r#"
(module
	(import "seal0" "seal_value_transferred" (func $seal_value_transferred (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the value transferred in the buffer
		(call $seal_value_transferred (i32.const 0) (i32.const 32))

		;; assert len == 8
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 8)
			)
		)

		;; assert that contents of the buffer is equal to the i64 value of 1337.
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 1337)
			)
		)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn value_transferred() {
		assert_ok!(execute(CODE_VALUE_TRANSFERRED, vec![], MockExt::default()));
	}

	const START_FN_ILLEGAL: &str = r#"
(module
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(start $start)
	(func $start
		(unreachable)
	)

	(func (export "call")
		(unreachable)
	)

	(func (export "deploy")
		(unreachable)
	)

	(data (i32.const 8) "\01\02\03\04")
)
"#;

	#[test]
	fn start_fn_illegal() {
		let output = execute(START_FN_ILLEGAL, vec![], MockExt::default());
		assert_err!(output, <Error<Test>>::CodeRejected,);
	}

	const CODE_TIMESTAMP_NOW: &str = r#"
(module
	(import "seal0" "seal_now" (func $seal_now (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the block timestamp in the buffer
		(call $seal_now (i32.const 0) (i32.const 32))

		;; assert len == 8
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 8)
			)
		)

		;; assert that contents of the buffer is equal to the i64 value of 1111.
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 1111)
			)
		)
	)
	(func (export "deploy"))
)
"#;

	const CODE_TIMESTAMP_NOW_UNPREFIXED: &str = r#"
(module
	(import "seal0" "now" (func $now (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the block timestamp in the buffer
		(call $now (i32.const 0) (i32.const 32))

		;; assert len == 8
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 8)
			)
		)

		;; assert that contents of the buffer is equal to the i64 value of 1111.
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 1111)
			)
		)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn now() {
		assert_ok!(execute(CODE_TIMESTAMP_NOW, vec![], MockExt::default()));
		assert_ok!(execute(CODE_TIMESTAMP_NOW_UNPREFIXED, vec![], MockExt::default()));
	}

	const CODE_MINIMUM_BALANCE: &str = r#"
(module
	(import "seal0" "seal_minimum_balance" (func $seal_minimum_balance (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		(call $seal_minimum_balance (i32.const 0) (i32.const 32))

		;; assert len == 8
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 8)
			)
		)

		;; assert that contents of the buffer is equal to the i64 value of 666.
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 666)
			)
		)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn minimum_balance() {
		assert_ok!(execute(CODE_MINIMUM_BALANCE, vec![], MockExt::default()));
	}

	const CODE_RANDOM: &str = r#"
(module
	(import "seal0" "seal_random" (func $seal_random (param i32 i32 i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; [0,128) is reserved for the result of PRNG.

	;; the subject used for the PRNG. [128,160)
	(data (i32.const 128)
		"\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F"
		"\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F"
	)

	;; size of our buffer is 128 bytes
	(data (i32.const 160) "\80")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the block random seed in the buffer
		(call $seal_random
			(i32.const 128) ;; Pointer in memory to the start of the subject buffer
			(i32.const 32) ;; The subject buffer's length
			(i32.const 0) ;; Pointer to the output buffer
			(i32.const 160) ;; Pointer to the output buffer length
		)

		;; assert len == 32
		(call $assert
			(i32.eq
				(i32.load (i32.const 160))
				(i32.const 32)
			)
		)

		;; return the random data
		(call $seal_return
			(i32.const 0)
			(i32.const 0)
			(i32.const 32)
		)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn random() {
		let output = execute_unvalidated(CODE_RANDOM, vec![], MockExt::default()).unwrap();

		// The mock ext just returns the same data that was passed as the subject.
		assert_eq!(
			output,
			ExecReturnValue {
				flags: ReturnFlags::empty(),
				data: array_bytes::hex_into_unchecked(
					"000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F"
				)
			},
		);
	}

	const CODE_RANDOM_V1: &str = r#"
(module
	(import "seal1" "seal_random" (func $seal_random (param i32 i32 i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; [0,128) is reserved for the result of PRNG.

	;; the subject used for the PRNG. [128,160)
	(data (i32.const 128)
		"\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F"
		"\00\01\02\03\04\05\06\07\08\09\0A\0B\0C\0D\0E\0F"
	)

	;; size of our buffer is 128 bytes
	(data (i32.const 160) "\80")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the block random seed in the buffer
		(call $seal_random
			(i32.const 128) ;; Pointer in memory to the start of the subject buffer
			(i32.const 32) ;; The subject buffer's length
			(i32.const 0) ;; Pointer to the output buffer
			(i32.const 160) ;; Pointer to the output buffer length
		)

		;; assert len == 32
		(call $assert
			(i32.eq
				(i32.load (i32.const 160))
				(i32.const 40)
			)
		)

		;; return the random data
		(call $seal_return
			(i32.const 0)
			(i32.const 0)
			(i32.const 40)
		)
	)
	(func (export "deploy"))
)
"#;

	#[test]
	fn random_v1() {
		let output = execute_unvalidated(CODE_RANDOM_V1, vec![], MockExt::default()).unwrap();

		// The mock ext just returns the same data that was passed as the subject.
		assert_eq!(
			output,
			ExecReturnValue {
				flags: ReturnFlags::empty(),
				data: (
					array_bytes::hex2array_unchecked::<_, 32>(
						"000102030405060708090A0B0C0D0E0F000102030405060708090A0B0C0D0E0F"
					),
					42u64,
				)
					.encode()
			},
		);
	}

	const CODE_DEPOSIT_EVENT: &str = r#"
(module
	(import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call")
		(call $seal_deposit_event
			(i32.const 32) ;; Pointer to the start of topics buffer
			(i32.const 33) ;; The length of the topics buffer.
			(i32.const 8) ;; Pointer to the start of the data buffer
			(i32.const 13) ;; Length of the buffer
		)
	)
	(func (export "deploy"))

	(data (i32.const 8) "\00\01\2A\00\00\00\00\00\00\00\E5\14\00")

	;; Encoded Vec<TopicOf<T>>, the buffer has length of 33 bytes.
	(data (i32.const 32) "\04\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33\33"
	"\33\33\33\33\33\33\33\33\33")
)
"#;

	#[test]
	fn deposit_event() {
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(CODE_DEPOSIT_EVENT, vec![], &mut mock_ext));

		assert_eq!(
			mock_ext.events,
			vec![(
				vec![H256::repeat_byte(0x33)],
				vec![0x00, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0x14, 0x00]
			)]
		);

		assert!(mock_ext.gas_meter.gas_left().ref_time() > 0);
	}

	const CODE_DEPOSIT_EVENT_DUPLICATES: &str = r#"
(module
	(import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call")
		(call $seal_deposit_event
			(i32.const 32) ;; Pointer to the start of topics buffer
			(i32.const 129) ;; The length of the topics buffer.
			(i32.const 8) ;; Pointer to the start of the data buffer
			(i32.const 13) ;; Length of the buffer
		)
	)
	(func (export "deploy"))

	(data (i32.const 8) "\00\01\2A\00\00\00\00\00\00\00\E5\14\00")

	;; Encoded Vec<TopicOf<T>>, the buffer has length of 129 bytes.
	(data (i32.const 32) "\10"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04")
)
"#;

	/// Checks that the runtime allows duplicate topics.
	#[test]
	fn deposit_event_duplicates_allowed() {
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(CODE_DEPOSIT_EVENT_DUPLICATES, vec![], &mut mock_ext,));

		assert_eq!(
			mock_ext.events,
			vec![(
				vec![
					H256::repeat_byte(0x01),
					H256::repeat_byte(0x02),
					H256::repeat_byte(0x01),
					H256::repeat_byte(0x04)
				],
				vec![0x00, 0x01, 0x2a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe5, 0x14, 0x00]
			)]
		);
	}

	const CODE_DEPOSIT_EVENT_MAX_TOPICS: &str = r#"
(module
	(import "seal0" "seal_deposit_event" (func $seal_deposit_event (param i32 i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call")
		(call $seal_deposit_event
			(i32.const 32) ;; Pointer to the start of topics buffer
			(i32.const 161) ;; The length of the topics buffer.
			(i32.const 8) ;; Pointer to the start of the data buffer
			(i32.const 13) ;; Length of the buffer
		)
	)
	(func (export "deploy"))

	(data (i32.const 8) "\00\01\2A\00\00\00\00\00\00\00\E5\14\00")

	;; Encoded Vec<TopicOf<T>>, the buffer has length of 161 bytes.
	(data (i32.const 32) "\14"
"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
"\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02"
"\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03\03"
"\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04\04"
"\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05\05")
)
"#;

	/// Checks that the runtime traps if there are more than `max_topic_events` topics.
	#[test]
	fn deposit_event_max_topics() {
		assert_eq!(
			execute(CODE_DEPOSIT_EVENT_MAX_TOPICS, vec![], MockExt::default(),),
			Err(ExecError {
				error: Error::<Test>::TooManyTopics.into(),
				origin: ErrorOrigin::Caller,
			})
		);
	}

	/// calls `seal_block_number` compares the result with the constant 121.
	const CODE_BLOCK_NUMBER: &str = r#"
(module
	(import "seal0" "seal_block_number" (func $seal_block_number (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; This stores the block height in the buffer
		(call $seal_block_number (i32.const 0) (i32.const 32))

		;; assert len == 8
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 8)
			)
		)

		;; assert that contents of the buffer is equal to the i64 value of 121.
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 121)
			)
		)
	)

	(func (export "deploy"))
)
"#;

	#[test]
	fn block_number() {
		let _ = execute(CODE_BLOCK_NUMBER, vec![], MockExt::default()).unwrap();
	}

	const CODE_RETURN_WITH_DATA: &str = r#"
(module
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(data (i32.const 32) "\20")

	;; Deploy routine is the same as call.
	(func (export "deploy")
		(call $call)
	)

	;; Call reads the first 4 bytes (LE) as the exit status and returns the rest as output data.
	(func $call (export "call")
		;; Copy input data this contract memory.
		(call $seal_input
			(i32.const 0)	;; Pointer where to store input
			(i32.const 32)	;; Pointer to the length of the buffer
		)

		;; Copy all but the first 4 bytes of the input data as the output data.
		(call $seal_return
			(i32.load (i32.const 0))
			(i32.const 4)
			(i32.sub (i32.load (i32.const 32)) (i32.const 4))
		)
		(unreachable)
	)
)
"#;

	#[test]
	fn seal_return_with_success_status() {
		let output = execute(
			CODE_RETURN_WITH_DATA,
			array_bytes::hex2bytes_unchecked("00000000445566778899"),
			MockExt::default(),
		)
		.unwrap();

		assert_eq!(
			output,
			ExecReturnValue {
				flags: ReturnFlags::empty(),
				data: array_bytes::hex2bytes_unchecked("445566778899"),
			}
		);
		assert!(!output.did_revert());
	}

	#[test]
	fn return_with_revert_status() {
		let output = execute(
			CODE_RETURN_WITH_DATA,
			array_bytes::hex2bytes_unchecked("010000005566778899"),
			MockExt::default(),
		)
		.unwrap();

		assert_eq!(
			output,
			ExecReturnValue {
				flags: ReturnFlags::REVERT,
				data: array_bytes::hex2bytes_unchecked("5566778899"),
			}
		);
		assert!(output.did_revert());
	}

	const CODE_OUT_OF_BOUNDS_ACCESS: &str = r#"
(module
	(import "seal0" "seal_terminate" (func $seal_terminate (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "deploy"))

	(func (export "call")
		(call $seal_terminate
			(i32.const 65536)  ;; Pointer to "account" address (out of bound).
			(i32.const 8)  ;; Length of "account" address.
		)
	)
)
"#;

	#[test]
	fn contract_out_of_bounds_access() {
		let mut mock_ext = MockExt::default();
		let result = execute(CODE_OUT_OF_BOUNDS_ACCESS, vec![], &mut mock_ext);

		assert_eq!(
			result,
			Err(ExecError {
				error: Error::<Test>::OutOfBounds.into(),
				origin: ErrorOrigin::Caller,
			})
		);
	}

	const CODE_DECODE_FAILURE: &str = r#"
(module
	(import "seal0" "seal_terminate" (func $seal_terminate (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "deploy"))

	(func (export "call")
		(call $seal_terminate
			(i32.const 0)  ;; Pointer to "account" address.
			(i32.const 4)  ;; Length of "account" address (too small -> decode fail).
		)
	)
)
"#;

	#[test]
	fn contract_decode_length_ignored() {
		let mut mock_ext = MockExt::default();
		let result = execute(CODE_DECODE_FAILURE, vec![], &mut mock_ext);
		// AccountID implements `MaxEncodeLen` and therefore the supplied length is
		// no longer needed nor used to determine how much is read from contract memory.
		assert_ok!(result);
	}

	#[test]
	fn debug_message_works() {
		const CODE_DEBUG_MESSAGE: &str = r#"
(module
	(import "seal0" "seal_debug_message" (func $seal_debug_message (param i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))

	(data (i32.const 0) "Hello World!")

	(func (export "call")
		(call $seal_debug_message
			(i32.const 0)	;; Pointer to the text buffer
			(i32.const 12)	;; The size of the buffer
		)
		drop
	)

	(func (export "deploy"))
)
"#;
		let mut ext = MockExt::default();
		execute(CODE_DEBUG_MESSAGE, vec![], &mut ext).unwrap();

		assert_eq!(std::str::from_utf8(&ext.debug_buffer).unwrap(), "Hello World!");
	}

	#[test]
	fn debug_message_invalid_utf8_fails() {
		const CODE_DEBUG_MESSAGE_FAIL: &str = r#"
(module
	(import "seal0" "seal_debug_message" (func $seal_debug_message (param i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))

	(data (i32.const 0) "\fc")

	(func (export "call")
		(call $seal_debug_message
			(i32.const 0)	;; Pointer to the text buffer
			(i32.const 1)	;; The size of the buffer
		)
		drop
	)

	(func (export "deploy"))
)
"#;
		let mut ext = MockExt::default();
		let result = execute(CODE_DEBUG_MESSAGE_FAIL, vec![], &mut ext);
		assert_ok!(result);
		assert!(ext.debug_buffer.is_empty());
	}

	const CODE_CALL_RUNTIME: &str = r#"
(module
	(import "seal0" "call_runtime" (func $call_runtime (param i32 i32) (result i32)))
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; 0x1000 = 4k in little endian
	;; size of input buffer
	(data (i32.const 0) "\00\10")

	(func (export "call")
		;; Receive the encoded call
		(call $seal_input
			(i32.const 4)	;; Pointer to the input buffer
			(i32.const 0)	;; Size of the length buffer
		)
		;; Just use the call passed as input and store result to memory
		(i32.store (i32.const 0)
			(call $call_runtime
				(i32.const 4)				;; Pointer where the call is stored
				(i32.load (i32.const 0))	;; Size of the call
			)
		)
		(call $seal_return
			(i32.const 0)	;; flags
			(i32.const 0)	;; returned value
			(i32.const 4)	;; length of returned value
		)
	)

	(func (export "deploy"))
)
"#;

	#[test]
	fn call_runtime_works() {
		let call =
			RuntimeCall::System(frame_system::Call::remark { remark: b"Hello World".to_vec() });
		let mut ext = MockExt::default();
		let result = execute(CODE_CALL_RUNTIME, call.encode(), &mut ext).unwrap();
		assert_eq!(*ext.runtime_calls.borrow(), vec![call]);
		// 0 = ReturnCode::Success
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0);
	}

	#[test]
	fn call_runtime_panics_on_invalid_call() {
		let mut ext = MockExt::default();
		let result = execute(CODE_CALL_RUNTIME, vec![0x42], &mut ext);
		assert_eq!(
			result,
			Err(ExecError {
				error: Error::<Test>::DecodingFailed.into(),
				origin: ErrorOrigin::Caller,
			})
		);
		assert_eq!(*ext.runtime_calls.borrow(), vec![]);
	}

	#[test]
	fn set_storage_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "seal2" "set_storage" (func $set_storage (param i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))

	;; [0, 4) size of input buffer
	;; 4k in little endian
	(data (i32.const 0) "\00\10")

	;; [4, 4100) input buffer

	(func (export "call")
		;; Receive (key ++ value_to_write)
		(call $seal_input
			(i32.const 4)	;; Pointer to the input buffer
			(i32.const 0)	;; Size of the input buffer
		)
		;; Store the passed value to the passed key and store result to memory
		(i32.store (i32.const 168)
			(call $set_storage
				(i32.const 8)				;; key_ptr
				(i32.load (i32.const 4))		;; key_len
				(i32.add				;; value_ptr = 8 + key_len
					(i32.const 8)
					(i32.load (i32.const 4)))
				(i32.sub				;; value_len (input_size - (key_len + key_len_len))
					(i32.load (i32.const 0))
					(i32.add
						(i32.load (i32.const 4))
						(i32.const 4)
					)
				)
			)
		)
		(call $seal_return
			(i32.const 0)	;; flags
			(i32.const 168)	;; ptr to returned value
			(i32.const 4)	;; length of returned value
		)
	)

	(func (export "deploy"))
)
"#;

		let mut ext = MockExt::default();

		// value did not exist before -> sentinel returned
		let input = (32, [1u8; 32], [42u8, 48]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL);
		assert_eq!(ext.storage.get(&[1u8; 32].to_vec()).unwrap(), &[42u8, 48]);

		// value do exist -> length of old value returned
		let input = (32, [1u8; 32], [0u8; 0]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 2);
		assert_eq!(ext.storage.get(&[1u8; 32].to_vec()).unwrap(), &[0u8; 0]);

		// value do exist -> length of old value returned (test for zero sized val)
		let input = (32, [1u8; 32], [99u8]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0);
		assert_eq!(ext.storage.get(&[1u8; 32].to_vec()).unwrap(), &[99u8]);
	}

	#[test]
	fn get_storage_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "seal1" "get_storage" (func $get_storage (param i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))

	;; [0, 4) size of input buffer (160 bytes as we copy the key+len here)
	(data (i32.const 0) "\A0")

	;; [4, 8) size of output buffer
	;; 4k in little endian
	(data (i32.const 4) "\00\10")

	;; [8, 168) input buffer
	;; [168, 4264) output buffer

	(func (export "call")
		;; Receive (key ++ value_to_write)
		(call $seal_input
			(i32.const 8)	;; Pointer to the input buffer
			(i32.const 0)	;; Size of the input buffer
		)
		;; Load a storage value and result of this call into the output buffer
		(i32.store (i32.const 168)
			(call $get_storage
				(i32.const 12)			;; key_ptr
				(i32.load (i32.const 8))	;; key_len
				(i32.const 172)			;; Pointer to the output buffer
				(i32.const 4)			;; Pointer to the size of the buffer
			)
		)
		(call $seal_return
			(i32.const 0)				;; flags
			(i32.const 168)				;; output buffer ptr
			(i32.add				;; length: output size + 4 (retval)
				(i32.load (i32.const 4))
				(i32.const 4)
			)
		)
	)

	(func (export "deploy"))
)
"#;

		let mut ext = MockExt::default();

		ext.set_storage(
			&Key::<Test>::try_from_var([1u8; 64].to_vec()).unwrap(),
			Some(vec![42u8]),
			false,
		)
		.unwrap();

		ext.set_storage(
			&Key::<Test>::try_from_var([2u8; 19].to_vec()).unwrap(),
			Some(vec![]),
			false,
		)
		.unwrap();

		// value does not exist
		let input = (63, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(
			u32::from_le_bytes(result.data[0..4].try_into().unwrap()),
			ReturnCode::KeyNotFound as u32
		);

		// value exists
		let input = (64, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(
			u32::from_le_bytes(result.data[0..4].try_into().unwrap()),
			ReturnCode::Success as u32
		);
		assert_eq!(ext.storage.get(&[1u8; 64].to_vec()).unwrap(), &[42u8]);
		assert_eq!(&result.data[4..], &[42u8]);

		// value exists (test for 0 sized)
		let input = (19, [2u8; 19]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(
			u32::from_le_bytes(result.data[0..4].try_into().unwrap()),
			ReturnCode::Success as u32
		);
		assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), Some(&vec![]));
		assert_eq!(&result.data[4..], &([] as [u8; 0]));
	}

	#[test]
	fn clear_storage_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "seal1" "clear_storage" (func $clear_storage (param i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))

	;; size of input buffer
	;; [0, 4) size of input buffer (128+32 = 160 bytes = 0xA0)
	(data (i32.const 0) "\A0")

	;; [4, 164) input buffer

	(func (export "call")
		;; Receive key
		(call $seal_input
			(i32.const 4)	;; Where we take input and store it
			(i32.const 0)	;; Where we take and store the length of thedata
		)
		;; Call seal_clear_storage and save what it returns at 0
		(i32.store (i32.const 0)
			(call $clear_storage
				(i32.const 8)			;; key_ptr
				(i32.load (i32.const 4))	;; key_len
			)
		)
		(call $seal_return
			(i32.const 0)	;; flags
			(i32.const 0)	;; returned value
			(i32.const 4)	;; length of returned value
		)
	)

	(func (export "deploy"))
)
"#;

		let mut ext = MockExt::default();

		ext.set_storage(
			&Key::<Test>::try_from_var([1u8; 64].to_vec()).unwrap(),
			Some(vec![42u8]),
			false,
		)
		.unwrap();
		ext.set_storage(
			&Key::<Test>::try_from_var([2u8; 19].to_vec()).unwrap(),
			Some(vec![]),
			false,
		)
		.unwrap();

		// value did not exist
		let input = (32, [3u8; 32]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		// sentinel returned
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL);
		assert_eq!(ext.storage.get(&[3u8; 32].to_vec()), None);

		// value did exist
		let input = (64, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		// length returned
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 1);
		// value cleared
		assert_eq!(ext.storage.get(&[1u8; 64].to_vec()), None);

		//value did not exist (wrong key length)
		let input = (63, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		// sentinel returned
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL);
		assert_eq!(ext.storage.get(&[1u8; 64].to_vec()), None);

		// value exists
		let input = (19, [2u8; 19]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		// length returned (test for 0 sized)
		assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0);
		// value cleared
		assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), None);
	}

	#[test]
	fn take_storage_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "seal0" "seal_input" (func $seal_input (param i32 i32)))
	(import "seal0" "take_storage" (func $take_storage (param i32 i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))

	;; [0, 4) size of input buffer (160 bytes as we copy the key+len here)
	(data (i32.const 0) "\A0")

	;; [4, 8) size of output buffer
	;; 4k in little endian
	(data (i32.const 4) "\00\10")

	;; [8, 168) input buffer
	;; [168, 4264) output buffer

	(func (export "call")
		;; Receive key
		(call $seal_input
			(i32.const 8)	;; Pointer to the input buffer
			(i32.const 0)	;; Size of the length buffer
		)

		;; Load a storage value and result of this call into the output buffer
		(i32.store (i32.const 168)
			(call $take_storage
				(i32.const 12)			;; key_ptr
				(i32.load (i32.const 8))	;; key_len
				(i32.const 172)			;; Pointer to the output buffer
				(i32.const 4)			;; Pointer to the size of the buffer
			)
		)

		;; Return the contents of the buffer
		(call $seal_return
			(i32.const 0)				;; flags
			(i32.const 168)				;; output buffer ptr
			(i32.add				;; length: storage size + 4 (retval)
				(i32.load (i32.const 4))
				(i32.const 4)
			)
		)
	)

	(func (export "deploy"))
)
"#;

		let mut ext = MockExt::default();

		ext.set_storage(
			&Key::<Test>::try_from_var([1u8; 64].to_vec()).unwrap(),
			Some(vec![42u8]),
			false,
		)
		.unwrap();

		ext.set_storage(
			&Key::<Test>::try_from_var([2u8; 19].to_vec()).unwrap(),
			Some(vec![]),
			false,
		)
		.unwrap();

		// value does not exist -> error returned
		let input = (63, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(
			u32::from_le_bytes(result.data[0..4].try_into().unwrap()),
			ReturnCode::KeyNotFound as u32
		);

		// value did exist -> value returned
		let input = (64, [1u8; 64]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(
			u32::from_le_bytes(result.data[0..4].try_into().unwrap()),
			ReturnCode::Success as u32
		);
		assert_eq!(ext.storage.get(&[1u8; 64].to_vec()), None);
		assert_eq!(&result.data[4..], &[42u8]);

		// value did exist -> length returned (test for 0 sized)
		let input = (19, [2u8; 19]).encode();
		let result = execute(CODE, input, &mut ext).unwrap();
		assert_eq!(
			u32::from_le_bytes(result.data[0..4].try_into().unwrap()),
			ReturnCode::Success as u32
		);
		assert_eq!(ext.storage.get(&[2u8; 19].to_vec()), None);
		assert_eq!(&result.data[4..], &[0u8; 0]);
	}

	#[test]
	fn is_contract_works() {
		const CODE_IS_CONTRACT: &str = r#"
;; This runs `is_contract` check on zero account address
(module
	(import "seal0" "seal_is_contract" (func $seal_is_contract (param i32) (result i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; [0, 32) zero-adress
	(data (i32.const 0)
		"\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00"
		"\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00\00"
	)

	;; [32, 36) here we store the return code of the `seal_is_contract`

	(func (export "deploy"))

	(func (export "call")
		(i32.store
			(i32.const 32)
			(call $seal_is_contract
				(i32.const 0) ;; ptr to destination address
			)
		)
		;; exit with success and take `seal_is_contract` return code to the output buffer
		(call $seal_return (i32.const 0) (i32.const 32) (i32.const 4))
	)
)
"#;
		let output = execute(CODE_IS_CONTRACT, vec![], MockExt::default()).unwrap();

		// The mock ext just always returns 1u32 (`true`).
		assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 1u32.encode() },);
	}

	#[test]
	fn code_hash_works() {
		/// calls `seal_code_hash` and compares the result with the constant.
		const CODE_CODE_HASH: &str = r#"
(module
	(import "seal0" "seal_code_hash" (func $seal_code_hash (param i32 i32 i32) (result i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; fill the buffer with the code hash.
		(call $seal_code_hash
			(i32.const 0) ;; input: address_ptr (before call)
			(i32.const 0) ;; output: code_hash_ptr (after call)
			(i32.const 32) ;; same 32 bytes length for input and output
		)

		;; assert size == 32
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 32)
			)
		)

		;; assert that the first 8 bytes are "1111111111111111"
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 0x1111111111111111)
			)
		)
		drop
	)

	(func (export "deploy"))
)
"#;
		assert_ok!(execute(CODE_CODE_HASH, vec![], MockExt::default()));
	}

	#[test]
	fn own_code_hash_works() {
		/// calls `seal_own_code_hash` and compares the result with the constant.
		const CODE_OWN_CODE_HASH: &str = r#"
(module
	(import "seal0" "seal_own_code_hash" (func $seal_own_code_hash (param i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; size of our buffer is 32 bytes
	(data (i32.const 32) "\20")

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)

	(func (export "call")
		;; fill the buffer with the code hash
		(call $seal_own_code_hash
			(i32.const 0)  ;; output: code_hash_ptr
			(i32.const 32) ;; 32 bytes length of code_hash output
		)

		;; assert size == 32
		(call $assert
			(i32.eq
				(i32.load (i32.const 32))
				(i32.const 32)
			)
		)

		;; assert that the first 8 bytes are "1010101010101010"
		(call $assert
			(i64.eq
				(i64.load (i32.const 0))
				(i64.const 0x1010101010101010)
			)
		)
	)

	(func (export "deploy"))
)
"#;
		assert_ok!(execute(CODE_OWN_CODE_HASH, vec![], MockExt::default()));
	}

	#[test]
	fn caller_is_origin_works() {
		const CODE_CALLER_IS_ORIGIN: &str = r#"
;; This runs `caller_is_origin` check on zero account address
(module
	(import "seal0" "seal_caller_is_origin" (func $seal_caller_is_origin (result i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; [0, 4) here the return code of the `seal_caller_is_origin` will be stored
	;; we initialize it with non-zero value to be sure that it's being overwritten below
	(data (i32.const 0) "\10\10\10\10")

	(func (export "deploy"))

	(func (export "call")
		(i32.store
			(i32.const 0)
			(call $seal_caller_is_origin)
		)
		;; exit with success and take `seal_caller_is_origin` return code to the output buffer
		(call $seal_return (i32.const 0) (i32.const 0) (i32.const 4))
	)
)
"#;
		let output = execute(CODE_CALLER_IS_ORIGIN, vec![], MockExt::default()).unwrap();

		// The mock ext just always returns 0u32 (`false`)
		assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 0u32.encode() },);
	}

	#[test]
	fn caller_is_root_works() {
		const CODE_CALLER_IS_ROOT: &str = r#"
;; This runs `caller_is_root` check on zero account address
(module
	(import "seal0" "caller_is_root" (func $caller_is_root (result i32)))
	(import "seal0" "seal_return" (func $seal_return (param i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	;; [0, 4) here the return code of the `caller_is_root` will be stored
	;; we initialize it with non-zero value to be sure that it's being overwritten below
	(data (i32.const 0) "\10\10\10\10")

	(func (export "deploy"))

	(func (export "call")
		(i32.store
			(i32.const 0)
			(call $caller_is_root)
		)
		;; exit with success and take `caller_is_root` return code to the output buffer
		(call $seal_return (i32.const 0) (i32.const 0) (i32.const 4))
	)
)
"#;
		// The default `caller` is ALICE. Therefore not root.
		let output = execute(CODE_CALLER_IS_ROOT, vec![], MockExt::default()).unwrap();
		assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 0u32.encode() },);

		// The caller is forced to be root instead of using the default ALICE.
		let output = execute(
			CODE_CALLER_IS_ROOT,
			vec![],
			MockExt { caller: Origin::Root, ..MockExt::default() },
		)
		.unwrap();
		assert_eq!(output, ExecReturnValue { flags: ReturnFlags::empty(), data: 1u32.encode() },);
	}

	#[test]
	fn set_code_hash() {
		const CODE: &str = r#"
(module
	(import "seal0" "seal_set_code_hash" (func $seal_set_code_hash (param i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)
	(func (export "call")
		(local $exit_code i32)
		(set_local $exit_code
			(call $seal_set_code_hash (i32.const 0))
		)
		(call $assert
			(i32.eq (get_local $exit_code) (i32.const 0)) ;; ReturnCode::Success
		)
	)

	(func (export "deploy"))

	;; Hash of code.
	(data (i32.const 0)
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
		"\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11\11"
	)
)
"#;

		let mut mock_ext = MockExt::default();
		execute(CODE, [0u8; 32].encode(), &mut mock_ext).unwrap();

		assert_eq!(mock_ext.code_hashes.pop().unwrap(), H256::from_slice(&[17u8; 32]));
	}

	#[test]
	fn reentrance_count_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "reentrance_count" (func $reentrance_count (result i32)))
	(import "env" "memory" (memory 1 1))
	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)
	(func (export "call")
		(local $return_val i32)
		(set_local $return_val
			(call $reentrance_count)
		)
		(call $assert
			(i32.eq (get_local $return_val) (i32.const 12))
		)
	)

	(func (export "deploy"))
)
"#;

		let mut mock_ext = MockExt::default();
		execute(CODE, vec![], &mut mock_ext).unwrap();
	}

	#[test]
	fn account_reentrance_count_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "account_reentrance_count" (func $account_reentrance_count (param i32) (result i32)))
	(import "env" "memory" (memory 1 1))
	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)
	(func (export "call")
		(local $return_val i32)
		(set_local $return_val
			(call $account_reentrance_count (i32.const 0))
		)
		(call $assert
			(i32.eq (get_local $return_val) (i32.const 12))
		)
	)

	(func (export "deploy"))
)
"#;

		let mut mock_ext = MockExt::default();
		execute(CODE, vec![], &mut mock_ext).unwrap();
	}

	#[test]
	fn instantiation_nonce_works() {
		const CODE: &str = r#"
(module
	(import "seal0" "instantiation_nonce" (func $nonce (result i64)))
	(import "env" "memory" (memory 1 1))

	(func $assert (param i32)
		(block $ok
			(br_if $ok
				(get_local 0)
			)
			(unreachable)
		)
	)
	(func (export "call")
		(call $assert
			(i64.eq (call $nonce) (i64.const 995))
		)
	)
	(func (export "deploy"))
)
"#;

		let mut mock_ext = MockExt::default();
		execute(CODE, vec![], &mut mock_ext).unwrap();
	}

	/// This test check that an unstable interface cannot be deployed. In case of runtime
	/// benchmarks we always allow unstable interfaces. This is why this test does not
	/// work when this feature is enabled.
	#[cfg(not(feature = "runtime-benchmarks"))]
	#[test]
	fn cannot_deploy_unstable() {
		const CANNOT_DEPLOY_UNSTABLE: &str = r#"
(module
	(import "seal0" "reentrance_count" (func $reentrance_count (result i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call"))
	(func (export "deploy"))
)
"#;
		assert_err!(
			execute_no_unstable(CANNOT_DEPLOY_UNSTABLE, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);
		assert_ok!(execute(CANNOT_DEPLOY_UNSTABLE, vec![], MockExt::default()));
	}

	/// The random interface is deprecated and hence new contracts using it should not be deployed.
	/// In case of runtime benchmarks we always allow deprecated interfaces. This is why this
	/// test doesn't work if this feature is enabled.
	#[cfg(not(feature = "runtime-benchmarks"))]
	#[test]
	fn cannot_deploy_deprecated() {
		const CODE_RANDOM_0: &str = r#"
(module
	(import "seal0" "seal_random" (func $seal_random (param i32 i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call"))
	(func (export "deploy"))
)
	"#;
		const CODE_RANDOM_1: &str = r#"
(module
	(import "seal1" "seal_random" (func $seal_random (param i32 i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call"))
	(func (export "deploy"))
)
	"#;
		const CODE_RANDOM_2: &str = r#"
(module
	(import "seal0" "random" (func $seal_random (param i32 i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call"))
	(func (export "deploy"))
)
	"#;
		const CODE_RANDOM_3: &str = r#"
(module
	(import "seal1" "random" (func $seal_random (param i32 i32 i32 i32)))
	(import "env" "memory" (memory 1 1))

	(func (export "call"))
	(func (export "deploy"))
)
	"#;

		assert_ok!(execute_unvalidated(CODE_RANDOM_0, vec![], MockExt::default()));
		assert_err!(
			execute_instantiate_unvalidated(CODE_RANDOM_0, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);
		assert_err!(
			execute(CODE_RANDOM_0, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);

		assert_ok!(execute_unvalidated(CODE_RANDOM_1, vec![], MockExt::default()));
		assert_err!(
			execute_instantiate_unvalidated(CODE_RANDOM_1, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);
		assert_err!(
			execute(CODE_RANDOM_1, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);

		assert_ok!(execute_unvalidated(CODE_RANDOM_2, vec![], MockExt::default()));
		assert_err!(
			execute_instantiate_unvalidated(CODE_RANDOM_2, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);
		assert_err!(
			execute(CODE_RANDOM_2, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);

		assert_ok!(execute_unvalidated(CODE_RANDOM_3, vec![], MockExt::default()));
		assert_err!(
			execute_instantiate_unvalidated(CODE_RANDOM_3, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);
		assert_err!(
			execute(CODE_RANDOM_3, vec![], MockExt::default()),
			<Error<Test>>::CodeRejected,
		);
	}

	#[test]
	fn add_remove_delegate_dependency() {
		const CODE_ADD_REMOVE_DELEGATE_DEPENDENCY: &str = r#"
(module
	(import "seal0" "add_delegate_dependency" (func $add_delegate_dependency (param i32)))
	(import "seal0" "remove_delegate_dependency" (func $remove_delegate_dependency (param i32)))
	(import "env" "memory" (memory 1 1))
	(func (export "call")
		(call $add_delegate_dependency (i32.const 0))
		(call $add_delegate_dependency (i32.const 32))
		(call $remove_delegate_dependency (i32.const 32))
	)
	(func (export "deploy"))

	;;  hash1 (32 bytes)
	(data (i32.const 0)
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
		"\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01\01"
	)

	;;  hash2 (32 bytes)
	(data (i32.const 32)
		"\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02"
		"\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02\02"
	)
)
"#;
		let mut mock_ext = MockExt::default();
		assert_ok!(execute(&CODE_ADD_REMOVE_DELEGATE_DEPENDENCY, vec![], &mut mock_ext));
		let delegate_dependencies: Vec<_> =
			mock_ext.delegate_dependencies.into_inner().into_iter().collect();
		assert_eq!(delegate_dependencies.len(), 1);
		assert_eq!(delegate_dependencies[0].as_bytes(), [1; 32]);
	}
}