pallet-revive 0.16.0

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

#![doc = include_str!("../README.md")]
#![allow(rustdoc::private_intra_doc_links)]
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "1024")]

extern crate alloc;

mod address;
mod benchmarking;
mod call_builder;
mod debug;
mod exec;
mod impl_fungibles;
mod limits;
mod metering;
mod primitives;
mod storage;
#[cfg(test)]
mod tests;
mod transient_storage;
mod vm;
mod weightinfo_extension;

pub mod evm;
pub mod migrations;
pub mod mock;
pub mod precompiles;
pub mod test_utils;
pub mod tracing;
pub mod weights;

use crate::{
	evm::{
		block_hash::EthereumBlockBuilderIR, block_storage, fees::InfoT as FeeInfo,
		runtime::SetWeightLimit, CallTracer, CreateCallMode, GenericTransaction, PrestateTracer,
		Trace, Tracer, TracerType, TYPE_EIP1559,
	},
	exec::{AccountIdOf, ExecError, ReentrancyProtection, Stack as ExecStack},
	storage::{AccountType, DeletionQueueManager},
	tracing::if_tracing,
	vm::{pvm::extract_code_and_data, CodeInfo, RuntimeCosts},
	weightinfo_extension::OnFinalizeBlockParts,
};
use alloc::{boxed::Box, format, vec};
use codec::{Codec, Decode, Encode};
use environmental::*;
use frame_support::{
	dispatch::{
		DispatchErrorWithPostInfo, DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo,
		Pays, PostDispatchInfo, RawOrigin,
	},
	ensure,
	pallet_prelude::DispatchClass,
	traits::{
		fungible::{Balanced, Inspect, Mutate, MutateHold},
		tokens::Balance,
		ConstU32, ConstU64, EnsureOrigin, Get, IsSubType, IsType, OriginTrait,
	},
	weights::WeightMeter,
	BoundedVec, RuntimeDebugNoBound,
};
use frame_system::{
	ensure_signed,
	pallet_prelude::{BlockNumberFor, OriginFor},
	Pallet as System,
};
use scale_info::TypeInfo;
use sp_runtime::{
	traits::{
		BadOrigin, Bounded, Convert, Dispatchable, Saturating, UniqueSaturatedFrom,
		UniqueSaturatedInto, Zero,
	},
	AccountId32, DispatchError, FixedPointNumber, FixedU128, SaturatedConversion,
};

pub use crate::{
	address::{
		create1, create2, is_eth_derived, AccountId32Mapper, AddressMapper, TestAccountMapper,
	},
	debug::DebugSettings,
	evm::{
		block_hash::ReceiptGasInfo, Address as EthAddress, Block as EthBlock, DryRunConfig,
		ReceiptInfo,
	},
	exec::{CallResources, DelegateInfo, Executable, Key, MomentOf, Origin as ExecOrigin},
	metering::{
		EthTxInfo, FrameMeter, ResourceMeter, Token as WeightToken, TransactionLimits,
		TransactionMeter,
	},
	pallet::{genesis, *},
	storage::{AccountInfo, ContractInfo},
	vm::{BytecodeType, ContractBlob},
};
pub use codec;
pub use frame_support::{self, dispatch::DispatchInfo, traits::Time, weights::Weight};
pub use frame_system::{self, limits::BlockWeights};
pub use primitives::*;
pub use sp_core::{keccak_256, H160, H256, U256};
pub use sp_runtime;
pub use weights::WeightInfo;

#[cfg(doc)]
pub use crate::vm::pvm::SyscallDoc;

pub type BalanceOf<T> = <T as Config>::Balance;
type TrieId = BoundedVec<u8, ConstU32<128>>;
type ImmutableData = BoundedVec<u8, ConstU32<{ limits::IMMUTABLE_BYTES }>>;
type CallOf<T> = <T as Config>::RuntimeCall;

/// Used as a sentinel value when reading and writing contract memory.
///
/// It is usually used to signal `None` to a contract when only a primitive is allowed
/// and we don't want to go through encoding a full Rust type. Using `u32::Max` is a safe
/// sentinel because contracts are never allowed to use such a large amount of resources
/// that this value makes sense for a memory location or length.
const SENTINEL: u32 = u32::MAX;

/// The target that is used for the log output emitted by this crate.
///
/// Hence you can use this target to selectively increase the log level for this crate.
///
/// Example: `RUST_LOG=runtime::revive=debug my_code --dev`
const LOG_TARGET: &str = "runtime::revive";

#[frame_support::pallet]
pub mod pallet {
	use super::*;
	use frame_support::{pallet_prelude::*, traits::FindAuthor};
	use frame_system::pallet_prelude::*;
	use sp_core::U256;
	use sp_runtime::Perbill;

	/// The in-code storage version.
	pub(crate) const STORAGE_VERSION: StorageVersion = StorageVersion::new(0);

	#[pallet::pallet]
	#[pallet::storage_version(STORAGE_VERSION)]
	pub struct Pallet<T>(_);

	#[pallet::config(with_default)]
	pub trait Config: frame_system::Config {
		/// The time implementation used to supply timestamps to contracts through `seal_now`.
		type Time: Time<Moment: Into<U256>>;

		/// The balance type of [`Self::Currency`].
		///
		/// Just added here to add additional trait bounds.
		#[pallet::no_default]
		type Balance: Balance
			+ TryFrom<U256>
			+ Into<U256>
			+ Bounded
			+ UniqueSaturatedInto<u64>
			+ UniqueSaturatedFrom<u64>
			+ UniqueSaturatedInto<u128>;

		/// The fungible in which fees are paid and contract balances are held.
		#[pallet::no_default]
		type Currency: Inspect<Self::AccountId, Balance = Self::Balance>
			+ Mutate<Self::AccountId>
			+ MutateHold<Self::AccountId, Reason = Self::RuntimeHoldReason>
			+ Balanced<Self::AccountId>;

		/// The overarching event type.
		#[pallet::no_default_bounds]
		#[allow(deprecated)]
		type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

		/// The overarching call type.
		#[pallet::no_default_bounds]
		type RuntimeCall: Parameter
			+ Dispatchable<
				RuntimeOrigin = OriginFor<Self>,
				Info = DispatchInfo,
				PostInfo = PostDispatchInfo,
			> + IsType<<Self as frame_system::Config>::RuntimeCall>
			+ From<Call<Self>>
			+ IsSubType<Call<Self>>
			+ GetDispatchInfo;

		/// The overarching origin type.
		#[pallet::no_default_bounds]
		type RuntimeOrigin: IsType<OriginFor<Self>>
			+ From<Origin<Self>>
			+ Into<Result<Origin<Self>, OriginFor<Self>>>;

		/// Overarching hold reason.
		#[pallet::no_default_bounds]
		type RuntimeHoldReason: From<HoldReason>;

		/// Describes the weights of the dispatchables of this module and is also used to
		/// construct a default cost schedule.
		type WeightInfo: WeightInfo;

		/// Type that allows the runtime authors to add new host functions for a contract to call.
		///
		/// Pass in a tuple of types that implement [`precompiles::Precompile`].
		#[pallet::no_default_bounds]
		#[allow(private_bounds)]
		type Precompiles: precompiles::Precompiles<Self>;

		/// Find the author of the current block.
		type FindAuthor: FindAuthor<Self::AccountId>;

		/// The amount of balance a caller has to pay for each byte of storage.
		///
		/// # Note
		///
		/// It is safe to change this value on a live chain as all refunds are pro rata.
		#[pallet::constant]
		#[pallet::no_default_bounds]
		type DepositPerByte: Get<BalanceOf<Self>>;

		/// The amount of balance a caller has to pay for each storage item.
		///
		/// # Note
		///
		/// It is safe to change this value on a live chain as all refunds are pro rata.
		#[pallet::constant]
		#[pallet::no_default_bounds]
		type DepositPerItem: Get<BalanceOf<Self>>;

		/// The amount of balance a caller has to pay for each child trie storage item.
		///
		/// Those are the items created by a contract. In Solidity each value is a single
		/// storage item. This is why we need to set a lower value here than for the main
		/// trie items. Otherwise the storage deposit is too high.
		///
		/// # Note
		///
		/// It is safe to change this value on a live chain as all refunds are pro rata.
		#[pallet::constant]
		#[pallet::no_default_bounds]
		type DepositPerChildTrieItem: Get<BalanceOf<Self>>;

		/// The percentage of the storage deposit that should be held for using a code hash.
		/// Instantiating a contract, protects the code from being removed. In order to prevent
		/// abuse these actions are protected with a percentage of the code deposit.
		#[pallet::constant]
		type CodeHashLockupDepositPercent: Get<Perbill>;

		/// Use either valid type is [`address::AccountId32Mapper`] or [`address::H160Mapper`].
		#[pallet::no_default]
		type AddressMapper: AddressMapper<Self>;

		/// Allow EVM bytecode to be uploaded and instantiated.
		#[pallet::constant]
		type AllowEVMBytecode: Get<bool>;

		/// Origin allowed to upload code.
		///
		/// By default, it is safe to set this to `EnsureSigned`, allowing anyone to upload contract
		/// code.
		#[pallet::no_default_bounds]
		type UploadOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;

		/// Origin allowed to instantiate code.
		///
		/// # Note
		///
		/// This is not enforced when a contract instantiates another contract. The
		/// [`Self::UploadOrigin`] should make sure that no code is deployed that does unwanted
		/// instantiations.
		///
		/// By default, it is safe to set this to `EnsureSigned`, allowing anyone to instantiate
		/// contract code.
		#[pallet::no_default_bounds]
		type InstantiateOrigin: EnsureOrigin<OriginFor<Self>, Success = Self::AccountId>;

		/// The amount of memory in bytes that parachain nodes a lot to the runtime.
		///
		/// This is used in [`Pallet::integrity_test`] to make sure that the runtime has enough
		/// memory to support this pallet if set to the correct value.
		type RuntimeMemory: Get<u32>;

		/// The amount of memory in bytes that relay chain validators a lot to the PoV.
		///
		/// This is used in [`Pallet::integrity_test`] to make sure that the runtime has enough
		/// memory to support this pallet if set to the correct value.
		///
		/// This value is usually higher than [`Self::RuntimeMemory`] to account for the fact
		/// that validators have to hold all storage items in PvF memory.
		type PVFMemory: Get<u32>;

		/// The [EIP-155](https://eips.ethereum.org/EIPS/eip-155) chain ID.
		///
		/// This is a unique identifier assigned to each blockchain network,
		/// preventing replay attacks.
		#[pallet::constant]
		type ChainId: Get<u64>;

		/// The ratio between the decimal representation of the native token and the ETH token.
		#[pallet::constant]
		type NativeToEthRatio: Get<u32>;

		/// Set to [`crate::evm::fees::Info`] for a production runtime.
		///
		/// For mock runtimes that do not need to interact with any eth compat functionality
		/// the default value of `()` will suffice.
		#[pallet::no_default_bounds]
		type FeeInfo: FeeInfo<Self>;

		/// The fraction the maximum extrinsic weight `eth_transact` extrinsics are capped to.
		///
		/// This is not a security measure but a requirement due to how we map gas to `(Weight,
		/// StorageDeposit)`. The mapping might derive a `Weight` that is too large to fit into an
		/// extrinsic. In this case we cap it to the limit specified here.
		///
		/// `eth_transact` transactions that use more weight than specified will fail with an out of
		/// gas error during execution. Larger fractions will allow more transactions to run.
		/// Smaller values waste less block space: Choose as small as possible and as large as
		/// necessary.
		///
		///  Default: `0.5`.
		#[pallet::constant]
		type MaxEthExtrinsicWeight: Get<FixedU128>;

		/// Allows debug-mode configuration, such as enabling unlimited contract size.
		#[pallet::constant]
		type DebugEnabled: Get<bool>;

		/// This determines the relative scale of our gas price and gas estimates.
		///
		/// By default, the gas price (in wei) is `FeeInfo::next_fee_multiplier()` multiplied by
		/// `NativeToEthRatio`. `GasScale` allows to scale this value: the actual gas price is the
		/// default gas price multiplied by `GasScale`.
		///
		/// As a consequence, gas cost (gas estimates and actual gas usage during transaction) is
		/// scaled down by the same factor. Thus, the total transaction cost is not affected by
		/// `GasScale` – apart from rounding differences: the transaction cost is always a multiple
		/// of the gas price and is derived by rounded up, so that with higher `GasScales` this can
		/// lead to higher gas cost as the rounding difference would be larger.
		///
		/// The main purpose of changing the `GasScale` is to tune the gas cost so that it is closer
		/// to standard EVM gas cost and contracts will not run out of gas when tools or code
		/// assume hard coded gas limits.
		///
		/// Requirement: `GasScale` must not be 0
		#[pallet::constant]
		#[pallet::no_default_bounds]
		type GasScale: Get<u32>;
	}

	/// Container for different types that implement [`DefaultConfig`]` of this pallet.
	pub mod config_preludes {
		use super::*;
		use frame_support::{
			derive_impl,
			traits::{ConstBool, ConstU32},
		};
		use frame_system::EnsureSigned;
		use sp_core::parameter_types;

		type Balance = u64;

		pub const DOLLARS: Balance = 1_000_000_000_000;
		pub const CENTS: Balance = DOLLARS / 100;
		pub const MILLICENTS: Balance = CENTS / 1_000;

		pub const fn deposit(items: u32, bytes: u32) -> Balance {
			items as Balance * 20 * CENTS + (bytes as Balance) * MILLICENTS
		}

		parameter_types! {
			pub const DepositPerItem: Balance = deposit(1, 0);
			pub const DepositPerChildTrieItem: Balance = deposit(1, 0) / 100;
			pub const DepositPerByte: Balance = deposit(0, 1);
			pub const CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0);
			pub const MaxEthExtrinsicWeight: FixedU128 = FixedU128::from_rational(9, 10);
			pub const GasScale: u32 = 10u32;
		}

		/// A type providing default configurations for this pallet in testing environment.
		pub struct TestDefaultConfig;

		impl Time for TestDefaultConfig {
			type Moment = u64;
			fn now() -> Self::Moment {
				0u64
			}
		}

		impl<T: From<u64>> Convert<Weight, T> for TestDefaultConfig {
			fn convert(w: Weight) -> T {
				w.ref_time().into()
			}
		}

		#[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)]
		impl frame_system::DefaultConfig for TestDefaultConfig {}

		#[frame_support::register_default_impl(TestDefaultConfig)]
		impl DefaultConfig for TestDefaultConfig {
			#[inject_runtime_type]
			type RuntimeEvent = ();

			#[inject_runtime_type]
			type RuntimeHoldReason = ();

			#[inject_runtime_type]
			type RuntimeCall = ();

			#[inject_runtime_type]
			type RuntimeOrigin = ();

			type Precompiles = ();
			type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent;
			type DepositPerByte = DepositPerByte;
			type DepositPerItem = DepositPerItem;
			type DepositPerChildTrieItem = DepositPerChildTrieItem;
			type Time = Self;
			type AllowEVMBytecode = ConstBool<true>;
			type UploadOrigin = EnsureSigned<Self::AccountId>;
			type InstantiateOrigin = EnsureSigned<Self::AccountId>;
			type WeightInfo = ();
			type RuntimeMemory = ConstU32<{ 128 * 1024 * 1024 }>;
			type PVFMemory = ConstU32<{ 512 * 1024 * 1024 }>;
			type ChainId = ConstU64<42>;
			type NativeToEthRatio = ConstU32<1_000_000>;
			type FindAuthor = ();
			type FeeInfo = ();
			type MaxEthExtrinsicWeight = MaxEthExtrinsicWeight;
			type DebugEnabled = ConstBool<false>;
			type GasScale = GasScale;
		}
	}

	#[pallet::event]
	pub enum Event<T: Config> {
		/// A custom event emitted by the contract.
		ContractEmitted {
			/// The contract that emitted the event.
			contract: H160,
			/// Data supplied by the contract. Metadata generated during contract compilation
			/// is needed to decode it.
			data: Vec<u8>,
			/// A list of topics used to index the event.
			/// Number of topics is capped by [`limits::NUM_EVENT_TOPICS`].
			topics: Vec<H256>,
		},

		/// Contract deployed by deployer at the specified address.
		Instantiated { deployer: H160, contract: H160 },

		/// Emitted when an Ethereum transaction reverts.
		///
		/// Ethereum transactions always complete successfully at the extrinsic level,
		/// as even reverted calls must store their `ReceiptInfo`.
		/// To distinguish reverted calls from successful ones, this event is emitted
		/// for failed Ethereum transactions.
		EthExtrinsicRevert { dispatch_error: DispatchError },
	}

	#[pallet::error]
	#[repr(u8)]
	pub enum Error<T> {
		/// Invalid schedule supplied, e.g. with zero weight of a basic operation.
		InvalidSchedule = 0x01,
		/// Invalid combination of flags supplied to `seal_call` or `seal_delegate_call`.
		InvalidCallFlags = 0x02,
		/// The executed contract exhausted its gas limit.
		OutOfGas = 0x03,
		/// Performing the requested transfer failed. Probably because there isn't enough
		/// free balance in the sender's account.
		TransferFailed = 0x04,
		/// Performing a call was denied because the calling depth reached the limit
		/// of what is specified in the schedule.
		MaxCallDepthReached = 0x05,
		/// No contract was found at the specified address.
		ContractNotFound = 0x06,
		/// No code could be found at the supplied code hash.
		CodeNotFound = 0x07,
		/// No code info could be found at the supplied code hash.
		CodeInfoNotFound = 0x08,
		/// A buffer outside of sandbox memory was passed to a contract API function.
		OutOfBounds = 0x09,
		/// Input passed to a contract API function failed to decode as expected type.
		DecodingFailed = 0x0A,
		/// Contract trapped during execution.
		ContractTrapped = 0x0B,
		/// Event body or storage item exceeds [`limits::STORAGE_BYTES`].
		ValueTooLarge = 0x0C,
		/// Termination of a contract is not allowed while the contract is already
		/// on the call stack. Can be triggered by `seal_terminate`.
		TerminatedWhileReentrant = 0x0D,
		/// `seal_call` forwarded this contracts input. It therefore is no longer available.
		InputForwarded = 0x0E,
		/// The amount of topics passed to `seal_deposit_events` exceeds the limit.
		TooManyTopics = 0x0F,
		/// A contract with the same AccountId already exists.
		DuplicateContract = 0x12,
		/// A contract self destructed in its constructor.
		///
		/// This can be triggered by a call to `seal_terminate`.
		TerminatedInConstructor = 0x13,
		/// A call tried to invoke a contract that is flagged as non-reentrant.
		ReentranceDenied = 0x14,
		/// A contract called into the runtime which then called back into this pallet.
		ReenteredPallet = 0x15,
		/// A contract attempted to invoke a state modifying API while being in read-only mode.
		StateChangeDenied = 0x16,
		/// Origin doesn't have enough balance to pay the required storage deposits.
		StorageDepositNotEnoughFunds = 0x17,
		/// More storage was created than allowed by the storage deposit limit.
		StorageDepositLimitExhausted = 0x18,
		/// Code removal was denied because the code is still in use by at least one contract.
		CodeInUse = 0x19,
		/// The contract ran to completion but decided to revert its storage changes.
		/// Please note that this error is only returned from extrinsics. When called directly
		/// or via RPC an `Ok` will be returned. In this case the caller needs to inspect the flags
		/// to determine whether a reversion has taken place.
		ContractReverted = 0x1A,
		/// The contract failed to compile or is missing the correct entry points.
		///
		/// A more detailed error can be found on the node console if debug messages are enabled
		/// by supplying `-lruntime::revive=debug`.
		CodeRejected = 0x1B,
		/// The code blob supplied is larger than [`limits::code::BLOB_BYTES`].
		BlobTooLarge = 0x1C,
		/// The contract declares too much memory (ro + rw + stack).
		StaticMemoryTooLarge = 0x1D,
		/// The program contains a basic block that is larger than allowed.
		BasicBlockTooLarge = 0x1E,
		/// The program contains an invalid instruction.
		InvalidInstruction = 0x1F,
		/// The contract has reached its maximum number of delegate dependencies.
		MaxDelegateDependenciesReached = 0x20,
		/// The dependency was not found in the contract's delegate dependencies.
		DelegateDependencyNotFound = 0x21,
		/// The contract already depends on the given delegate dependency.
		DelegateDependencyAlreadyExists = 0x22,
		/// Can not add a delegate dependency to the code hash of the contract itself.
		CannotAddSelfAsDelegateDependency = 0x23,
		/// Can not add more data to transient storage.
		OutOfTransientStorage = 0x24,
		/// The contract tried to call a syscall which does not exist (at its current api level).
		InvalidSyscall = 0x25,
		/// Invalid storage flags were passed to one of the storage syscalls.
		InvalidStorageFlags = 0x26,
		/// PolkaVM failed during code execution. Probably due to a malformed program.
		ExecutionFailed = 0x27,
		/// Failed to convert a U256 to a Balance.
		BalanceConversionFailed = 0x28,
		/// Immutable data can only be set during deploys and only be read during calls.
		/// Additionally, it is only valid to set the data once and it must not be empty.
		InvalidImmutableAccess = 0x2A,
		/// An `AccountID32` account tried to interact with the pallet without having a mapping.
		///
		/// Call [`Pallet::map_account`] in order to create a mapping for the account.
		AccountUnmapped = 0x2B,
		/// Tried to map an account that is already mapped.
		AccountAlreadyMapped = 0x2C,
		/// The transaction used to dry-run a contract is invalid.
		InvalidGenericTransaction = 0x2D,
		/// The refcount of a code either over or underflowed.
		RefcountOverOrUnderflow = 0x2E,
		/// Unsupported precompile address.
		UnsupportedPrecompileAddress = 0x2F,
		/// The calldata exceeds [`limits::CALLDATA_BYTES`].
		CallDataTooLarge = 0x30,
		/// The return data exceeds [`limits::CALLDATA_BYTES`].
		ReturnDataTooLarge = 0x31,
		/// Invalid jump destination. Dynamic jumps points to invalid not jumpdest opcode.
		InvalidJump = 0x32,
		/// Attempting to pop a value from an empty stack.
		StackUnderflow = 0x33,
		/// Attempting to push a value onto a full stack.
		StackOverflow = 0x34,
		/// Too much deposit was drawn from the shared txfee and deposit credit.
		///
		/// This happens if the passed `gas` inside the ethereum transaction is too low.
		TxFeeOverdraw = 0x35,
		/// When calling an EVM constructor `data` has to be empty.
		///
		/// EVM constructors do not accept data. Their input data is part of the code blob itself.
		EvmConstructorNonEmptyData = 0x36,
		/// Tried to construct an EVM contract via code hash.
		///
		/// EVM contracts can only be instantiated via code upload as no initcode is
		/// stored on-chain.
		EvmConstructedFromHash = 0x37,
		/// The contract does not have enough balance to refund the storage deposit.
		///
		/// This is a bug and should never happen. It means the accounting got out of sync.
		StorageRefundNotEnoughFunds = 0x38,
		/// This means there are locks on the contracts storage deposit that prevents refunding it.
		///
		/// This would be the case if the contract used its storage deposits for governance
		/// or other pallets that allow creating locks over held balance.
		StorageRefundLocked = 0x39,
		/// Called a pre-compile that is not allowed to be delegate called.
		///
		/// Some pre-compile functions will trap the caller context if being delegate
		/// called or if their caller was being delegate called.
		PrecompileDelegateDenied = 0x40,
		/// ECDSA public key recovery failed. Most probably wrong recovery id or signature.
		EcdsaRecoveryFailed = 0x41,
		/// Benchmarking only error.
		#[cfg(feature = "runtime-benchmarks")]
		BenchmarkingError = 0xFF,
	}

	/// A reason for the pallet revive placing a hold on funds.
	#[pallet::composite_enum]
	pub enum HoldReason {
		/// The Pallet has reserved it for storing code on-chain.
		CodeUploadDepositReserve,
		/// The Pallet has reserved it for storage deposit.
		StorageDepositReserve,
		/// Deposit for creating an address mapping in [`OriginalAccount`].
		AddressMapping,
	}

	#[derive(
		PartialEq,
		Eq,
		Clone,
		MaxEncodedLen,
		Encode,
		Decode,
		DecodeWithMemTracking,
		TypeInfo,
		RuntimeDebug,
	)]
	#[pallet::origin]
	pub enum Origin<T: Config> {
		EthTransaction(T::AccountId),
	}

	/// A mapping from a contract's code hash to its code.
	/// The code's size is bounded by [`crate::limits::BLOB_BYTES`] for PVM and
	/// [`revm::primitives::eip170::MAX_CODE_SIZE`] for EVM bytecode.
	#[pallet::storage]
	#[pallet::unbounded]
	pub(crate) type PristineCode<T: Config> = StorageMap<_, Identity, H256, Vec<u8>>;

	/// A mapping from a contract's code hash to its code info.
	#[pallet::storage]
	pub(crate) type CodeInfoOf<T: Config> = StorageMap<_, Identity, H256, CodeInfo<T>>;

	/// The data associated to a contract or externally owned account.
	#[pallet::storage]
	pub(crate) type AccountInfoOf<T: Config> = StorageMap<_, Identity, H160, AccountInfo<T>>;

	/// The immutable data associated with a given account.
	#[pallet::storage]
	pub(crate) type ImmutableDataOf<T: Config> = StorageMap<_, Identity, H160, ImmutableData>;

	/// Evicted contracts that await child trie deletion.
	///
	/// Child trie deletion is a heavy operation depending on the amount of storage items
	/// stored in said trie. Therefore this operation is performed lazily in `on_idle`.
	#[pallet::storage]
	pub(crate) type DeletionQueue<T: Config> = StorageMap<_, Twox64Concat, u32, TrieId>;

	/// A pair of monotonic counters used to track the latest contract marked for deletion
	/// and the latest deleted contract in queue.
	#[pallet::storage]
	pub(crate) type DeletionQueueCounter<T: Config> =
		StorageValue<_, DeletionQueueManager<T>, ValueQuery>;

	/// Map a Ethereum address to its original `AccountId32`.
	///
	/// When deriving a `H160` from an `AccountId32` we use a hash function. In order to
	/// reconstruct the original account we need to store the reverse mapping here.
	/// Register your `AccountId32` using [`Pallet::map_account`] in order to
	/// use it with this pallet.
	#[pallet::storage]
	pub(crate) type OriginalAccount<T: Config> = StorageMap<_, Identity, H160, AccountId32>;

	/// The current Ethereum block that is stored in the `on_finalize` method.
	///
	/// # Note
	///
	/// This could be further optimized into the future to store only the minimum
	/// information needed to reconstruct the Ethereum block at the RPC level.
	///
	/// Since the block is convenient to have around, and the extra details are capped
	/// by a few hashes and the vector of transaction hashes, we store the block here.
	#[pallet::storage]
	#[pallet::unbounded]
	pub(crate) type EthereumBlock<T> = StorageValue<_, EthBlock, ValueQuery>;

	/// Mapping for block number and hashes.
	///
	/// The maximum number of elements stored is capped by the block hash count `BLOCK_HASH_COUNT`.
	#[pallet::storage]
	pub(crate) type BlockHash<T: Config> =
		StorageMap<_, Identity, BlockNumberFor<T>, H256, ValueQuery>;

	/// The details needed to reconstruct the receipt info offchain.
	///
	/// This contains valuable information about the gas used by the transaction.
	///
	/// NOTE: The item is unbound and should therefore never be read on chain.
	/// It could otherwise inflate the PoV size of a block.
	#[pallet::storage]
	#[pallet::unbounded]
	pub(crate) type ReceiptInfoData<T: Config> = StorageValue<_, Vec<ReceiptGasInfo>, ValueQuery>;

	/// Incremental ethereum block builder.
	#[pallet::storage]
	#[pallet::unbounded]
	pub(crate) type EthBlockBuilderIR<T: Config> =
		StorageValue<_, EthereumBlockBuilderIR<T>, ValueQuery>;

	/// The first transaction and receipt of the ethereum block.
	///
	/// These values are moved out of the `EthBlockBuilderIR` to avoid serializing and
	/// deserializing them on every transaction. Instead, they are loaded when needed.
	#[pallet::storage]
	#[pallet::unbounded]
	pub(crate) type EthBlockBuilderFirstValues<T: Config> =
		StorageValue<_, Option<(Vec<u8>, Vec<u8>)>, ValueQuery>;

	/// Debugging settings that can be configured when DebugEnabled config is true.
	#[pallet::storage]
	pub(crate) type DebugSettingsOf<T: Config> = StorageValue<_, DebugSettings, ValueQuery>;

	pub mod genesis {
		use super::*;
		use crate::evm::Bytes32;

		/// Genesis configuration for contract-specific data.
		#[derive(Clone, PartialEq, Debug, Default, serde::Serialize, serde::Deserialize)]
		pub struct ContractData {
			/// Contract code.
			pub code: Vec<u8>,
			/// Initial storage entries as 32-byte key/value pairs.
			pub storage: alloc::collections::BTreeMap<Bytes32, Bytes32>,
		}

		/// Genesis configuration for a contract account.
		#[derive(PartialEq, Default, Debug, Clone, serde::Serialize, serde::Deserialize)]
		pub struct Account<T: Config> {
			/// Contract address.
			pub address: H160,
			/// Contract balance.
			#[serde(default)]
			pub balance: U256,
			/// Account nonce
			#[serde(default)]
			pub nonce: T::Nonce,
			/// Contract-specific data (code and storage). None for EOAs.
			#[serde(flatten, skip_serializing_if = "Option::is_none")]
			pub contract_data: Option<ContractData>,
		}
	}

	#[pallet::genesis_config]
	#[derive(Debug, PartialEq, frame_support::DefaultNoBound)]
	pub struct GenesisConfig<T: Config> {
		/// List of native Substrate accounts (typically `AccountId32`) to be mapped at genesis
		/// block, enabling them to interact with smart contracts.
		#[serde(default, skip_serializing_if = "Vec::is_empty")]
		pub mapped_accounts: Vec<T::AccountId>,

		/// Account entries (both EOAs and contracts)
		#[serde(default, skip_serializing_if = "Vec::is_empty")]
		pub accounts: Vec<genesis::Account<T>>,

		/// Optional debugging settings applied at genesis.
		#[serde(default, skip_serializing_if = "Option::is_none")]
		pub debug_settings: Option<DebugSettings>,
	}

	#[pallet::genesis_build]
	impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
		fn build(&self) {
			use crate::{exec::Key, vm::ContractBlob};
			use frame_support::traits::fungible::Mutate;

			if !System::<T>::account_exists(&Pallet::<T>::account_id()) {
				let _ = T::Currency::mint_into(
					&Pallet::<T>::account_id(),
					T::Currency::minimum_balance(),
				);
			}

			for id in &self.mapped_accounts {
				if let Err(err) = T::AddressMapper::map_no_deposit(id) {
					log::error!(target: LOG_TARGET, "Failed to map account {id:?}: {err:?}");
				}
			}

			let owner = Pallet::<T>::account_id();

			for genesis::Account { address, balance, nonce, contract_data } in &self.accounts {
				let account_id = T::AddressMapper::to_account_id(address);

				if !System::<T>::account_exists(&account_id) {
					let _ = T::Currency::mint_into(&account_id, T::Currency::minimum_balance());
				}

				frame_system::Account::<T>::mutate(&account_id, |info| {
					info.nonce = (*nonce).into();
				});

				match contract_data {
					None => {
						AccountInfoOf::<T>::insert(
							address,
							AccountInfo { account_type: AccountType::EOA, dust: 0 },
						);
					},
					Some(genesis::ContractData { code, storage }) => {
						let blob = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
							ContractBlob::<T>::from_pvm_code(   code.clone(), owner.clone()).inspect_err(|err| {
								log::error!(target: LOG_TARGET, "Failed to create PVM ContractBlob for {address:?}: {err:?}");
							})
						} else {
							ContractBlob::<T>::from_evm_runtime_code(code.clone(), account_id).inspect_err(|err| {
								log::error!(target: LOG_TARGET, "Failed to create EVM ContractBlob for {address:?}: {err:?}");
							})
						};

						let Ok(blob) = blob else {
							continue;
						};

						let code_hash = *blob.code_hash();
						let Ok(info) = <ContractInfo<T>>::new(&address, 0u32.into(), code_hash)
							.inspect_err(|err| {
								log::error!(target: LOG_TARGET, "Failed to create ContractInfo for {address:?}: {err:?}");
							})
						else {
							continue;
						};

						AccountInfoOf::<T>::insert(
							address,
							AccountInfo { account_type: info.clone().into(), dust: 0 },
						);

						<PristineCode<T>>::insert(blob.code_hash(), code);
						<CodeInfoOf<T>>::insert(blob.code_hash(), blob.code_info().clone());
						for (k, v) in storage {
							let _ = info.write(&Key::from_fixed(k.0), Some(v.0.to_vec()), None, false).inspect_err(|err| {
								log::error!(target: LOG_TARGET, "Failed to write genesis storage for {address:?} at key {k:?}: {err:?}");
							});
						}
					},
				}

				let _ = Pallet::<T>::set_evm_balance(address, *balance).inspect_err(|err| {
					log::error!(target: LOG_TARGET, "Failed to set EVM balance for {address:?}: {err:?}");
				});
			}

			// Build genesis block
			block_storage::on_finalize_build_eth_block::<T>(
				// Make sure to use the block number from storage instead of the hardcoded 0.
				// This enables testing tools like anvil to customise the genesis block number.
				frame_system::Pallet::<T>::block_number(),
			);

			// Set debug settings.
			if let Some(settings) = self.debug_settings.as_ref() {
				settings.write_to_storage::<T>()
			}
		}
	}

	#[pallet::hooks]
	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
		fn on_idle(_block: BlockNumberFor<T>, limit: Weight) -> Weight {
			let mut meter = WeightMeter::with_limit(limit);
			ContractInfo::<T>::process_deletion_queue_batch(&mut meter);
			meter.consumed()
		}

		fn on_initialize(_n: BlockNumberFor<T>) -> Weight {
			// Kill related ethereum block storage items.
			block_storage::on_initialize::<T>();

			// Warm up the pallet account.
			System::<T>::account_exists(&Pallet::<T>::account_id());
			// Account for the fixed part of the costs incurred in `on_finalize`.
			<T as Config>::WeightInfo::on_finalize_block_fixed()
		}

		fn on_finalize(block_number: BlockNumberFor<T>) {
			// Build the ethereum block and place it in storage.
			block_storage::on_finalize_build_eth_block::<T>(block_number);
		}

		fn integrity_test() {
			assert!(T::ChainId::get() > 0, "ChainId must be greater than 0");

			assert!(T::GasScale::get() > 0u32.into(), "GasScale must not be 0");

			T::FeeInfo::integrity_test();

			// The memory available in the block building runtime
			let max_runtime_mem: u64 = T::RuntimeMemory::get().into();

			// We only allow 50% of the runtime memory to be utilized by the contracts call
			// stack, keeping the rest for other facilities, such as PoV, etc.
			const TOTAL_MEMORY_DEVIDER: u64 = 2;

			// Validators are configured to be able to use more memory than block builders. This is
			// because in addition to `max_runtime_mem` they need to hold additional data in
			// memory: PoV in multiple copies (1x encoded + 2x decoded) and all storage which
			// includes emitted events. The assumption is that storage/events size
			// can be a maximum of half of the validator runtime memory - max_runtime_mem.
			let max_block_weight = T::BlockWeights::get()
				.get(DispatchClass::Normal)
				.max_total
				.unwrap_or_else(|| T::BlockWeights::get().max_block);
			let max_key_size: u64 =
				Key::try_from_var(alloc::vec![0u8; limits::STORAGE_KEY_BYTES as usize])
					.expect("Key of maximal size shall be created")
					.hash()
					.len()
					.try_into()
					.unwrap();

			let max_immutable_key_size: u64 = T::AccountId::max_encoded_len().try_into().unwrap();
			let max_immutable_size: u64 = max_block_weight
				.checked_div_per_component(&<RuntimeCosts as WeightToken<T>>::weight(
					&RuntimeCosts::SetImmutableData(limits::IMMUTABLE_BYTES),
				))
				.unwrap()
				.saturating_mul(
					u64::from(limits::IMMUTABLE_BYTES)
						.saturating_add(max_immutable_key_size)
						.into(),
				);

			let max_pvf_mem: u64 = T::PVFMemory::get().into();
			let storage_size_limit = max_pvf_mem.saturating_sub(max_runtime_mem) / 2;

			// We can use storage to store events using the available block ref_time with the
			// `deposit_event` host function. The overhead of stored events, which is around 100B,
			// is not taken into account to simplify calculations, as it does not change much.
			let max_events_size = max_block_weight
				.checked_div_per_component(
					&(<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::DepositEvent {
						num_topic: 0,
						len: limits::EVENT_BYTES,
					})
					.saturating_add(<RuntimeCosts as WeightToken<T>>::weight(
						&RuntimeCosts::HostFn,
					))),
				)
				.unwrap()
				.saturating_mul(limits::EVENT_BYTES.into());

			assert!(
				max_events_size <= storage_size_limit,
				"Maximal events size {} exceeds the events limit {}",
				max_events_size,
				storage_size_limit
			);

			// The incremental block builder uses 3 x maximum entry size for receipts and
			// for transactions. Transactions are bounded to `MAX_TRANSACTION_PAYLOAD_SIZE`.
			//
			// To determine the maximum size of the receipts, we know the following:
			// - (I) first receipt is stored into pallet storage and not given to the hasher until
			//   finalization.
			// - (II) the hasher will not consume more memory than the receipts we are giving it.
			// - (III) the hasher is capped by 3 x maximum entry for 3 or more transactions.
			//
			// # Case 1. One transaction with maximum receipts
			//
			// The worst case scenario for having one single transaction is for the transaction
			// to emit the maximum receipt size (ie `max_events_size`). In this case,
			// the maximum storage (and memory) consumed is bounded by `max_events_size` (II). The
			// receipt is stored in pallet storage, and loaded from storage in the
			// `on_finalize` hook (I).
			//
			// # Case 2. Two transactions
			//
			// The sum of the receipt size of both transactions cannot exceed `max_events_size`,
			// otherwise one transaction will be reverted. From (II), the bytes utilized
			// by the builder are capped to `max_events_size`.
			//
			// # Case 3. Three or more transactions
			//
			// Similar to the above case, the sum of all receipt size is bounded to
			// `max_events_size`. Therefore, the bytes are capped to `max_events_size`.
			//
			// On average, a transaction could emit `max_events_size / num_tx`. The would
			// consume `max_events_size / num_tx * 3` bytes, which is lower than
			// `max_events_size` for more than 3 transactions.
			//
			// In practice, the builder will consume even lower amounts considering
			// it is unlikely for a transaction to utilize all the weight of the block for events.
			let max_eth_block_builder_bytes =
				block_storage::block_builder_bytes_usage(max_events_size.try_into().unwrap());

			log::debug!(
				target: LOG_TARGET,
				"Integrity check: max_eth_block_builder_bytes={} KB using max_events_size={} KB",
				max_eth_block_builder_bytes / 1024,
				max_events_size / 1024,
			);

			// Check that the configured memory limits fit into runtime memory.
			//
			// Dynamic allocations are not available, yet. Hence they are not taken into
			// consideration here.
			let memory_left = i128::from(max_runtime_mem)
				.saturating_div(TOTAL_MEMORY_DEVIDER.into())
				.saturating_sub(limits::MEMORY_REQUIRED.into())
				.saturating_sub(max_eth_block_builder_bytes.into());

			log::debug!(target: LOG_TARGET, "Integrity check: memory_left={} KB", memory_left / 1024);

			assert!(
				memory_left >= 0,
				"Runtime does not have enough memory for current limits. Additional runtime memory required: {} KB",
				memory_left.saturating_mul(TOTAL_MEMORY_DEVIDER.into()).abs() / 1024
			);

			// We can use storage to store items using the available block ref_time with the
			// `set_storage` host function.
			let max_storage_size = max_block_weight
				.checked_div_per_component(
					&<RuntimeCosts as WeightToken<T>>::weight(&RuntimeCosts::SetStorage {
						new_bytes: limits::STORAGE_BYTES,
						old_bytes: 0,
					})
					.saturating_mul(u64::from(limits::STORAGE_BYTES).saturating_add(max_key_size)),
				)
				.unwrap()
				.saturating_add(max_immutable_size.into())
				.saturating_add(max_eth_block_builder_bytes.into());

			assert!(
				max_storage_size <= storage_size_limit,
				"Maximal storage size {} exceeds the storage limit {}",
				max_storage_size,
				storage_size_limit
			);
		}
	}

	#[pallet::call]
	impl<T: Config> Pallet<T> {
		/// A raw EVM transaction, typically dispatched by an Ethereum JSON-RPC server.
		///
		/// # Parameters
		///
		/// * `payload`: The encoded [`crate::evm::TransactionSigned`].
		///
		/// # Note
		///
		/// This call cannot be dispatched directly; attempting to do so will result in a failed
		/// transaction. It serves as a wrapper for an Ethereum transaction. When submitted, the
		/// runtime converts it into a [`sp_runtime::generic::CheckedExtrinsic`] by recovering the
		/// signer and validating the transaction.
		#[allow(unused_variables)]
		#[pallet::call_index(0)]
		#[pallet::weight(Weight::MAX)]
		pub fn eth_transact(origin: OriginFor<T>, payload: Vec<u8>) -> DispatchResultWithPostInfo {
			Err(frame_system::Error::CallFiltered::<T>.into())
		}

		/// Makes a call to an account, optionally transferring some balance.
		///
		/// # Parameters
		///
		/// * `dest`: Address of the contract to call.
		/// * `value`: The balance to transfer from the `origin` to `dest`.
		/// * `weight_limit`: The weight limit enforced when executing the constructor.
		/// * `storage_deposit_limit`: The maximum amount of balance that can be charged from the
		///   caller to pay for the storage consumed.
		/// * `data`: The input data to pass to the contract.
		///
		/// * If the account is a smart-contract account, the associated code will be
		/// executed and any value will be transferred.
		/// * If the account is a regular account, any value will be transferred.
		/// * If no account exists and the call value is not less than `existential_deposit`,
		/// a regular account will be created and any value will be transferred.
		#[pallet::call_index(1)]
		#[pallet::weight(<T as Config>::WeightInfo::call().saturating_add(*weight_limit))]
		pub fn call(
			origin: OriginFor<T>,
			dest: H160,
			#[pallet::compact] value: BalanceOf<T>,
			weight_limit: Weight,
			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
			data: Vec<u8>,
		) -> DispatchResultWithPostInfo {
			Self::ensure_non_contract_if_signed(&origin)?;
			let mut output = Self::bare_call(
				origin,
				dest,
				Pallet::<T>::convert_native_to_evm(value),
				TransactionLimits::WeightAndDeposit {
					weight_limit,
					deposit_limit: storage_deposit_limit,
				},
				data,
				ExecConfig::new_substrate_tx(),
			);

			if let Ok(return_value) = &output.result {
				if return_value.did_revert() {
					output.result = Err(<Error<T>>::ContractReverted.into());
				}
			}
			dispatch_result(
				output.result,
				output.weight_consumed,
				<T as Config>::WeightInfo::call(),
			)
		}

		/// Instantiates a contract from a previously deployed vm binary.
		///
		/// This function is identical to [`Self::instantiate_with_code`] but without the
		/// code deployment step. Instead, the `code_hash` of an on-chain deployed vm binary
		/// must be supplied.
		#[pallet::call_index(2)]
		#[pallet::weight(
			<T as Config>::WeightInfo::instantiate(data.len() as u32).saturating_add(*weight_limit)
		)]
		pub fn instantiate(
			origin: OriginFor<T>,
			#[pallet::compact] value: BalanceOf<T>,
			weight_limit: Weight,
			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
			code_hash: sp_core::H256,
			data: Vec<u8>,
			salt: Option<[u8; 32]>,
		) -> DispatchResultWithPostInfo {
			Self::ensure_non_contract_if_signed(&origin)?;
			let data_len = data.len() as u32;
			let mut output = Self::bare_instantiate(
				origin,
				Pallet::<T>::convert_native_to_evm(value),
				TransactionLimits::WeightAndDeposit {
					weight_limit,
					deposit_limit: storage_deposit_limit,
				},
				Code::Existing(code_hash),
				data,
				salt,
				ExecConfig::new_substrate_tx(),
			);
			if let Ok(retval) = &output.result {
				if retval.result.did_revert() {
					output.result = Err(<Error<T>>::ContractReverted.into());
				}
			}
			dispatch_result(
				output.result.map(|result| result.result),
				output.weight_consumed,
				<T as Config>::WeightInfo::instantiate(data_len),
			)
		}

		/// Instantiates a new contract from the supplied `code` optionally transferring
		/// some balance.
		///
		/// This dispatchable has the same effect as calling [`Self::upload_code`] +
		/// [`Self::instantiate`]. Bundling them together provides efficiency gains. Please
		/// also check the documentation of [`Self::upload_code`].
		///
		/// # Parameters
		///
		/// * `value`: The balance to transfer from the `origin` to the newly created contract.
		/// * `weight_limit`: The weight limit enforced when executing the constructor.
		/// * `storage_deposit_limit`: The maximum amount of balance that can be charged/reserved
		///   from the caller to pay for the storage consumed.
		/// * `code`: The contract code to deploy in raw bytes.
		/// * `data`: The input data to pass to the contract constructor.
		/// * `salt`: Used for the address derivation. If `Some` is supplied then `CREATE2`
		/// 	semantics are used. If `None` then `CRATE1` is used.
		///
		///
		/// Instantiation is executed as follows:
		///
		/// - The supplied `code` is deployed, and a `code_hash` is created for that code.
		/// - If the `code_hash` already exists on the chain the underlying `code` will be shared.
		/// - The destination address is computed based on the sender, code_hash and the salt.
		/// - The smart-contract account is created at the computed address.
		/// - The `value` is transferred to the new account.
		/// - The `deploy` function is executed in the context of the newly-created account.
		#[pallet::call_index(3)]
		#[pallet::weight(
			<T as Config>::WeightInfo::instantiate_with_code(code.len() as u32, data.len() as u32)
			.saturating_add(*weight_limit)
		)]
		pub fn instantiate_with_code(
			origin: OriginFor<T>,
			#[pallet::compact] value: BalanceOf<T>,
			weight_limit: Weight,
			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
			code: Vec<u8>,
			data: Vec<u8>,
			salt: Option<[u8; 32]>,
		) -> DispatchResultWithPostInfo {
			Self::ensure_non_contract_if_signed(&origin)?;
			let code_len = code.len() as u32;
			let data_len = data.len() as u32;
			let mut output = Self::bare_instantiate(
				origin,
				Pallet::<T>::convert_native_to_evm(value),
				TransactionLimits::WeightAndDeposit {
					weight_limit,
					deposit_limit: storage_deposit_limit,
				},
				Code::Upload(code),
				data,
				salt,
				ExecConfig::new_substrate_tx(),
			);
			if let Ok(retval) = &output.result {
				if retval.result.did_revert() {
					output.result = Err(<Error<T>>::ContractReverted.into());
				}
			}
			dispatch_result(
				output.result.map(|result| result.result),
				output.weight_consumed,
				<T as Config>::WeightInfo::instantiate_with_code(code_len, data_len),
			)
		}

		/// Same as [`Self::instantiate_with_code`], but intended to be dispatched **only**
		/// by an EVM transaction through the EVM compatibility layer.
		///
		/// # Parameters
		///
		/// * `value`: The balance to transfer from the `origin` to the newly created contract.
		/// * `weight_limit`: The gas limit used to derive the transaction weight for transaction
		///   payment
		/// * `eth_gas_limit`: The Ethereum gas limit governing the resource usage of the execution
		/// * `code`: The contract code to deploy in raw bytes.
		/// * `data`: The input data to pass to the contract constructor.
		/// * `transaction_encoded`: The RLP encoding of the signed Ethereum transaction,
		///   represented as [crate::evm::TransactionSigned], provided by the Ethereum wallet. This
		///   is used for building the Ethereum transaction root.
		/// * effective_gas_price: the price of a unit of gas
		/// * encoded len: the byte code size of the `eth_transact` extrinsic
		///
		/// Calling this dispatchable ensures that the origin's nonce is bumped only once,
		/// via the `CheckNonce` transaction extension. In contrast, [`Self::instantiate_with_code`]
		/// also bumps the nonce after contract instantiation, since it may be invoked multiple
		/// times within a batch call transaction.
		#[pallet::call_index(10)]
		#[pallet::weight(
			<T as Config>::WeightInfo::eth_instantiate_with_code(code.len() as u32, data.len() as u32, Pallet::<T>::has_dust(*value).into())
			.saturating_add(*weight_limit)
		)]
		pub fn eth_instantiate_with_code(
			origin: OriginFor<T>,
			value: U256,
			weight_limit: Weight,
			eth_gas_limit: U256,
			code: Vec<u8>,
			data: Vec<u8>,
			transaction_encoded: Vec<u8>,
			effective_gas_price: U256,
			encoded_len: u32,
		) -> DispatchResultWithPostInfo {
			let signer = Self::ensure_eth_signed(origin)?;
			let origin = OriginFor::<T>::signed(signer.clone());
			Self::ensure_non_contract_if_signed(&origin)?;
			let mut call = Call::<T>::eth_instantiate_with_code {
				value,
				weight_limit,
				eth_gas_limit,
				code: code.clone(),
				data: data.clone(),
				transaction_encoded: transaction_encoded.clone(),
				effective_gas_price,
				encoded_len,
			}
			.into();
			let info = T::FeeInfo::dispatch_info(&call);
			let base_info = T::FeeInfo::base_dispatch_info(&mut call);
			drop(call);

			block_storage::with_ethereum_context::<T>(transaction_encoded, || {
				let extra_weight = base_info.total_weight();
				let output = Self::bare_instantiate(
					origin,
					value,
					TransactionLimits::EthereumGas {
						eth_gas_limit: eth_gas_limit.saturated_into(),
						maybe_weight_limit: Some(weight_limit),
						eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
					},
					Code::Upload(code),
					data,
					None,
					ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
				);

				block_storage::EthereumCallResult::new::<T>(
					signer,
					output.map_result(|r| r.result),
					base_info.call_weight,
					encoded_len,
					&info,
					effective_gas_price,
				)
			})
		}

		/// Same as [`Self::call`], but intended to be dispatched **only**
		/// by an EVM transaction through the EVM compatibility layer.
		///
		/// # Parameters
		///
		/// * `dest`: The Ethereum address of the account to be called
		/// * `value`: The balance to transfer from the `origin` to the newly created contract.
		/// * `weight_limit`: The gas limit used to derive the transaction weight for transaction
		///   payment
		/// * `eth_gas_limit`: The Ethereum gas limit governing the resource usage of the execution
		/// * `data`: The input data to pass to the contract constructor.
		/// * `transaction_encoded`: The RLP encoding of the signed Ethereum transaction,
		///   represented as [crate::evm::TransactionSigned], provided by the Ethereum wallet. This
		///   is used for building the Ethereum transaction root.
		/// * effective_gas_price: the price of a unit of gas
		/// * encoded len: the byte code size of the `eth_transact` extrinsic
		#[pallet::call_index(11)]
		#[pallet::weight(
			T::WeightInfo::eth_call(Pallet::<T>::has_dust(*value).into())
			.saturating_add(*weight_limit)
			.saturating_add(T::WeightInfo::on_finalize_block_per_tx(transaction_encoded.len() as u32))
		)]
		pub fn eth_call(
			origin: OriginFor<T>,
			dest: H160,
			value: U256,
			weight_limit: Weight,
			eth_gas_limit: U256,
			data: Vec<u8>,
			transaction_encoded: Vec<u8>,
			effective_gas_price: U256,
			encoded_len: u32,
		) -> DispatchResultWithPostInfo {
			let signer = Self::ensure_eth_signed(origin)?;
			let origin = OriginFor::<T>::signed(signer.clone());

			Self::ensure_non_contract_if_signed(&origin)?;
			let mut call = Call::<T>::eth_call {
				dest,
				value,
				weight_limit,
				eth_gas_limit,
				data: data.clone(),
				transaction_encoded: transaction_encoded.clone(),
				effective_gas_price,
				encoded_len,
			}
			.into();
			let info = T::FeeInfo::dispatch_info(&call);
			let base_info = T::FeeInfo::base_dispatch_info(&mut call);
			drop(call);

			block_storage::with_ethereum_context::<T>(transaction_encoded, || {
				let extra_weight = base_info.total_weight();
				let output = Self::bare_call(
					origin,
					dest,
					value,
					TransactionLimits::EthereumGas {
						eth_gas_limit: eth_gas_limit.saturated_into(),
						maybe_weight_limit: Some(weight_limit),
						eth_tx_info: EthTxInfo::new(encoded_len, extra_weight),
					},
					data,
					ExecConfig::new_eth_tx(effective_gas_price, encoded_len, extra_weight),
				);

				block_storage::EthereumCallResult::new::<T>(
					signer,
					output,
					base_info.call_weight,
					encoded_len,
					&info,
					effective_gas_price,
				)
			})
		}

		/// Executes a Substrate runtime call from an Ethereum transaction.
		///
		/// This dispatchable is intended to be called **only** through the EVM compatibility
		/// layer. The provided call will be dispatched using `RawOrigin::Signed`.
		///
		/// # Parameters
		///
		/// * `origin`: Must be an [`Origin::EthTransaction`] origin.
		/// * `call`: The Substrate runtime call to execute.
		/// * `transaction_encoded`: The RLP encoding of the Ethereum transaction,
		#[pallet::call_index(12)]
		#[pallet::weight(T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32).saturating_add(call.get_dispatch_info().call_weight))]
		pub fn eth_substrate_call(
			origin: OriginFor<T>,
			call: Box<<T as Config>::RuntimeCall>,
			transaction_encoded: Vec<u8>,
		) -> DispatchResultWithPostInfo {
			// Note that the inner dispatch uses `RawOrigin::Signed`, which cannot
			// re-enter `eth_substrate_call` (which requires `Origin::EthTransaction`).
			let signer = Self::ensure_eth_signed(origin)?;
			let weight_overhead =
				T::WeightInfo::eth_substrate_call(transaction_encoded.len() as u32);

			block_storage::with_ethereum_context::<T>(transaction_encoded, || {
				let call_weight = call.get_dispatch_info().call_weight;
				let mut call_result = call.dispatch(RawOrigin::Signed(signer).into());

				// Add extrinsic_overhead to the actual weight in PostDispatchInfo
				match &mut call_result {
					Ok(post_info) | Err(DispatchErrorWithPostInfo { post_info, .. }) => {
						post_info.actual_weight = Some(
							post_info
								.actual_weight
								.unwrap_or_else(|| call_weight)
								.saturating_add(weight_overhead),
						);
					},
				}

				// Return zero EVM gas (Substrate dispatch, not EVM contract call).
				// Actual weight is in `post_info.actual_weight`.
				block_storage::EthereumCallResult {
					receipt_gas_info: ReceiptGasInfo::default(),
					result: call_result,
				}
			})
		}

		/// Upload new `code` without instantiating a contract from it.
		///
		/// If the code does not already exist a deposit is reserved from the caller
		/// The size of the reserve depends on the size of the supplied `code`.
		///
		/// # Note
		///
		/// Anyone can instantiate a contract from any uploaded code and thus prevent its removal.
		/// To avoid this situation a constructor could employ access control so that it can
		/// only be instantiated by permissioned entities. The same is true when uploading
		/// through [`Self::instantiate_with_code`].
		///
		/// If the refcount of the code reaches zero after terminating the last contract that
		/// references this code, the code will be removed automatically.
		#[pallet::call_index(4)]
		#[pallet::weight(<T as Config>::WeightInfo::upload_code(code.len() as u32))]
		pub fn upload_code(
			origin: OriginFor<T>,
			code: Vec<u8>,
			#[pallet::compact] storage_deposit_limit: BalanceOf<T>,
		) -> DispatchResult {
			Self::ensure_non_contract_if_signed(&origin)?;
			Self::bare_upload_code(origin, code, storage_deposit_limit).map(|_| ())
		}

		/// Remove the code stored under `code_hash` and refund the deposit to its owner.
		///
		/// A code can only be removed by its original uploader (its owner) and only if it is
		/// not used by any contract.
		#[pallet::call_index(5)]
		#[pallet::weight(<T as Config>::WeightInfo::remove_code())]
		pub fn remove_code(
			origin: OriginFor<T>,
			code_hash: sp_core::H256,
		) -> DispatchResultWithPostInfo {
			let origin = ensure_signed(origin)?;
			<ContractBlob<T>>::remove(&origin, code_hash)?;
			// we waive the fee because removing unused code is beneficial
			Ok(Pays::No.into())
		}

		/// Privileged function that changes the code of an existing contract.
		///
		/// This takes care of updating refcounts and all other necessary operations. Returns
		/// an error if either the `code_hash` or `dest` do not exist.
		///
		/// # Note
		///
		/// This does **not** change the address of the contract in question. This means
		/// that the contract address is no longer derived from its code hash after calling
		/// this dispatchable.
		#[pallet::call_index(6)]
		#[pallet::weight(<T as Config>::WeightInfo::set_code())]
		pub fn set_code(
			origin: OriginFor<T>,
			dest: H160,
			code_hash: sp_core::H256,
		) -> DispatchResult {
			ensure_root(origin)?;
			<AccountInfoOf<T>>::try_mutate(&dest, |account| {
				let Some(account) = account else {
					return Err(<Error<T>>::ContractNotFound.into());
				};

				let AccountType::Contract(ref mut contract) = account.account_type else {
					return Err(<Error<T>>::ContractNotFound.into());
				};

				<CodeInfo<T>>::increment_refcount(code_hash)?;
				let _ = <CodeInfo<T>>::decrement_refcount(contract.code_hash)?;
				contract.code_hash = code_hash;

				Ok(())
			})
		}

		/// Register the callers account id so that it can be used in contract interactions.
		///
		/// This will error if the origin is already mapped or is a eth native `Address20`. It will
		/// take a deposit that can be released by calling [`Self::unmap_account`].
		#[pallet::call_index(7)]
		#[pallet::weight(<T as Config>::WeightInfo::map_account())]
		pub fn map_account(origin: OriginFor<T>) -> DispatchResult {
			Self::ensure_non_contract_if_signed(&origin)?;
			let origin = ensure_signed(origin)?;
			T::AddressMapper::map(&origin)
		}

		/// Unregister the callers account id in order to free the deposit.
		///
		/// There is no reason to ever call this function other than freeing up the deposit.
		/// This is only useful when the account should no longer be used.
		#[pallet::call_index(8)]
		#[pallet::weight(<T as Config>::WeightInfo::unmap_account())]
		pub fn unmap_account(origin: OriginFor<T>) -> DispatchResult {
			let origin = ensure_signed(origin)?;
			T::AddressMapper::unmap(&origin)
		}

		/// Dispatch an `call` with the origin set to the callers fallback address.
		///
		/// Every `AccountId32` can control its corresponding fallback account. The fallback account
		/// is the `AccountId20` with the last 12 bytes set to `0xEE`. This is essentially a
		/// recovery function in case an `AccountId20` was used without creating a mapping first.
		#[pallet::call_index(9)]
		#[pallet::weight({
			let dispatch_info = call.get_dispatch_info();
			(
				<T as Config>::WeightInfo::dispatch_as_fallback_account().saturating_add(dispatch_info.call_weight),
				dispatch_info.class
			)
		})]
		pub fn dispatch_as_fallback_account(
			origin: OriginFor<T>,
			call: Box<<T as Config>::RuntimeCall>,
		) -> DispatchResultWithPostInfo {
			Self::ensure_non_contract_if_signed(&origin)?;
			let origin = ensure_signed(origin)?;
			let unmapped_account =
				T::AddressMapper::to_fallback_account_id(&T::AddressMapper::to_address(&origin));
			call.dispatch(RawOrigin::Signed(unmapped_account).into())
		}
	}
}

/// Create a dispatch result reflecting the amount of consumed weight.
fn dispatch_result<R>(
	result: Result<R, DispatchError>,
	weight_consumed: Weight,
	base_weight: Weight,
) -> DispatchResultWithPostInfo {
	let post_info = PostDispatchInfo {
		actual_weight: Some(weight_consumed.saturating_add(base_weight)),
		pays_fee: Default::default(),
	};

	result
		.map(|_| post_info)
		.map_err(|e| DispatchErrorWithPostInfo { post_info, error: e })
}

impl<T: Config> Pallet<T> {
	/// A generalized version of [`Self::call`].
	///
	/// Identical to [`Self::call`] but tailored towards being called by other code within the
	/// runtime as opposed to from an extrinsic. It returns more information and allows the
	/// enablement of features that are not suitable for an extrinsic (debugging, event
	/// collection).
	pub fn bare_call(
		origin: OriginFor<T>,
		dest: H160,
		evm_value: U256,
		transaction_limits: TransactionLimits<T>,
		data: Vec<u8>,
		exec_config: ExecConfig<T>,
	) -> ContractResult<ExecReturnValue, BalanceOf<T>> {
		let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
			Ok(transaction_meter) => transaction_meter,
			Err(error) => return ContractResult { result: Err(error), ..Default::default() },
		};

		let mut storage_deposit = Default::default();

		let try_call = || {
			let origin = ExecOrigin::from_runtime_origin(origin)?;
			let result = ExecStack::<T, ContractBlob<T>>::run_call(
				origin.clone(),
				dest,
				&mut transaction_meter,
				evm_value,
				data,
				&exec_config,
			)?;

			storage_deposit = transaction_meter
				.execute_postponed_deposits(&origin, &exec_config)
				.inspect_err(|err| {
				log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
			})?;

			Ok(result)
		};
		let result = Self::run_guarded(try_call);

		log::trace!(target: LOG_TARGET, "Bare call ends: \
			result={result:?}, \
			weight_consumed={:?}, \
			weight_required={:?}, \
			storage_deposit={:?}, \
			gas_consumed={:?}, \
			max_storage_deposit={:?}",
			transaction_meter.weight_consumed(),
			transaction_meter.weight_required(),
			storage_deposit,
			transaction_meter.total_consumed_gas(),
			transaction_meter.deposit_required()
		);

		ContractResult {
			result: result.map_err(|r| r.error),
			weight_consumed: transaction_meter.weight_consumed(),
			weight_required: transaction_meter.weight_required(),
			storage_deposit,
			gas_consumed: transaction_meter.total_consumed_gas(),
			max_storage_deposit: transaction_meter.deposit_required(),
		}
	}

	/// Prepare a dry run for the given account.
	///
	///
	/// This function is public because it is called by the runtime API implementation
	/// (see `impl_runtime_apis_plus_revive`).
	pub fn prepare_dry_run(account: &T::AccountId) {
		// Bump the  nonce to simulate what would happen
		// `pre-dispatch` if the transaction was executed.
		frame_system::Pallet::<T>::inc_account_nonce(account);
	}

	/// A generalized version of [`Self::instantiate`] or [`Self::instantiate_with_code`].
	///
	/// Identical to [`Self::instantiate`] or [`Self::instantiate_with_code`] but tailored towards
	/// being called by other code within the runtime as opposed to from an extrinsic. It returns
	/// more information to the caller useful to estimate the cost of the operation.
	pub fn bare_instantiate(
		origin: OriginFor<T>,
		evm_value: U256,
		transaction_limits: TransactionLimits<T>,
		code: Code,
		data: Vec<u8>,
		salt: Option<[u8; 32]>,
		exec_config: ExecConfig<T>,
	) -> ContractResult<InstantiateReturnValue, BalanceOf<T>> {
		let mut transaction_meter = match TransactionMeter::new(transaction_limits) {
			Ok(transaction_meter) => transaction_meter,
			Err(error) => return ContractResult { result: Err(error), ..Default::default() },
		};

		let mut storage_deposit = Default::default();

		let try_instantiate = || {
			let instantiate_account = T::InstantiateOrigin::ensure_origin(origin.clone())?;

			if_tracing(|t| t.instantiate_code(&code, salt.as_ref()));
			let executable = match code {
				Code::Upload(code) if code.starts_with(&polkavm_common::program::BLOB_MAGIC) => {
					let upload_account = T::UploadOrigin::ensure_origin(origin)?;
					let executable = Self::try_upload_code(
						upload_account,
						code,
						BytecodeType::Pvm,
						&mut transaction_meter,
						&exec_config,
					)?;
					executable
				},
				Code::Upload(code) =>
					if T::AllowEVMBytecode::get() {
						ensure!(data.is_empty(), <Error<T>>::EvmConstructorNonEmptyData);
						let origin = T::UploadOrigin::ensure_origin(origin)?;
						let executable = ContractBlob::from_evm_init_code(code, origin)?;
						executable
					} else {
						return Err(<Error<T>>::CodeRejected.into())
					},
				Code::Existing(code_hash) => {
					let executable = ContractBlob::from_storage(code_hash, &mut transaction_meter)?;
					ensure!(executable.code_info().is_pvm(), <Error<T>>::EvmConstructedFromHash);
					executable
				},
			};
			let instantiate_origin = ExecOrigin::from_account_id(instantiate_account.clone());
			let result = ExecStack::<T, ContractBlob<T>>::run_instantiate(
				instantiate_account,
				executable,
				&mut transaction_meter,
				evm_value,
				data,
				salt.as_ref(),
				&exec_config,
			);

			storage_deposit = transaction_meter
				.execute_postponed_deposits(&instantiate_origin, &exec_config)
				.inspect_err(|err| {
					log::debug!(target: LOG_TARGET, "Failed to transfer deposit: {err:?}");
				})?;
			result
		};
		let output = Self::run_guarded(try_instantiate);

		log::trace!(target: LOG_TARGET, "Bare instantiate ends: weight_consumed={:?}\
			weight_required={:?} \
			storage_deposit={:?} \
			gas_consumed={:?} \
			max_storage_deposit={:?}",
			transaction_meter.weight_consumed(),
			transaction_meter.weight_required(),
			storage_deposit,
			transaction_meter.total_consumed_gas(),
			transaction_meter.deposit_required()
		);

		ContractResult {
			result: output
				.map(|(addr, result)| InstantiateReturnValue { result, addr })
				.map_err(|e| e.error),
			weight_consumed: transaction_meter.weight_consumed(),
			weight_required: transaction_meter.weight_required(),
			storage_deposit,
			gas_consumed: transaction_meter.total_consumed_gas(),
			max_storage_deposit: transaction_meter.deposit_required(),
		}
	}

	/// Dry-run Ethereum calls.
	///
	/// # Parameters
	///
	/// - `tx`: The Ethereum transaction to simulate.
	pub fn dry_run_eth_transact(
		mut tx: GenericTransaction,
		dry_run_config: DryRunConfig<<<T as Config>::Time as Time>::Moment>,
	) -> Result<EthTransactInfo<BalanceOf<T>>, EthTransactError>
	where
		T::Nonce: Into<U256>,
		CallOf<T>: SetWeightLimit,
	{
		log::debug!(target: LOG_TARGET, "dry_run_eth_transact: {tx:?}");

		let origin = T::AddressMapper::to_account_id(&tx.from.unwrap_or_default());
		Self::prepare_dry_run(&origin);

		let base_fee = Self::evm_base_fee();
		let effective_gas_price = tx.effective_gas_price(base_fee).unwrap_or(base_fee);

		if effective_gas_price < base_fee {
			Err(EthTransactError::Message(format!(
				"Effective gas price {effective_gas_price:?} lower than base fee {base_fee:?}"
			)))?;
		}

		if tx.nonce.is_none() {
			tx.nonce = Some(<System<T>>::account_nonce(&origin).into());
		}
		if tx.chain_id.is_none() {
			tx.chain_id = Some(T::ChainId::get().into());
		}

		// tx.into_call expects tx.gas_price to be the effective gas price
		tx.gas_price = Some(effective_gas_price);
		// we don't support priority fee for now as the tipping system in pallet-transaction-payment
		// works differently and the total tip needs to be known pre dispatch
		tx.max_priority_fee_per_gas = Some(0.into());
		if tx.max_fee_per_gas.is_none() {
			tx.max_fee_per_gas = Some(effective_gas_price);
		}

		let gas = tx.gas;
		if tx.gas.is_none() {
			tx.gas = Some(Self::evm_block_gas_limit());
		}
		if tx.r#type.is_none() {
			tx.r#type = Some(TYPE_EIP1559.into());
		}

		// Store values before moving the tx
		let value = tx.value.unwrap_or_default();
		let input = tx.input.clone().to_vec();
		let from = tx.from;
		let to = tx.to;

		// we need to parse the weight from the transaction so that it is run
		// using the exact weight limit passed by the eth wallet
		let mut call_info = tx
			.into_call::<T>(CreateCallMode::DryRun)
			.map_err(|err| EthTransactError::Message(format!("Invalid call: {err:?}")))?;

		// the dry-run might leave out certain fields
		// in those cases we skip the check that the caller has enough balance
		// to pay for the fees
		let base_info = T::FeeInfo::base_dispatch_info(&mut call_info.call);
		let base_weight = base_info.total_weight();
		let exec_config =
			ExecConfig::new_eth_tx(effective_gas_price, call_info.encoded_len, base_weight)
				.with_dry_run(dry_run_config);

		// emulate transaction behavior
		let fees = call_info.tx_fee.saturating_add(call_info.storage_deposit);
		if let Some(from) = &from {
			let fees = if gas.is_some() { fees } else { Zero::zero() };
			let balance = Self::evm_balance(from);
			if balance < Pallet::<T>::convert_native_to_evm(fees).saturating_add(value) {
				return Err(EthTransactError::Message(format!(
					"insufficient funds for gas * price + value ({fees:?}): address {from:?} have {balance:?} (supplied gas {gas:?})",
				)));
			}
		}

		// the deposit is done when the transaction is transformed from an `eth_transact`
		// we emulate this behavior for the dry-run here
		T::FeeInfo::deposit_txfee(T::Currency::issue(fees));

		let extract_error = |err| {
			if err == Error::<T>::StorageDepositNotEnoughFunds.into() {
				Err(EthTransactError::Message(format!("Not enough gas supplied: {err:?}")))
			} else {
				Err(EthTransactError::Message(format!("failed to run contract: {err:?}")))
			}
		};

		let transaction_limits = TransactionLimits::EthereumGas {
			eth_gas_limit: call_info.eth_gas_limit.saturated_into(),
			// no need to limit weight here, we will check later whether it exceeds
			// evm_max_extrinsic_weight
			maybe_weight_limit: None,
			eth_tx_info: EthTxInfo::new(call_info.encoded_len, base_weight),
		};

		// Dry run the call
		let mut dry_run = match to {
			// A contract call.
			Some(dest) => {
				if dest == RUNTIME_PALLETS_ADDR {
					let Ok(dispatch_call) = <CallOf<T>>::decode(&mut &input[..]) else {
						return Err(EthTransactError::Message(format!(
							"Failed to decode pallet-call {input:?}"
						)));
					};

					if let Err(result) =
						dispatch_call.clone().dispatch(RawOrigin::Signed(origin).into())
					{
						return Err(EthTransactError::Message(format!(
							"Failed to dispatch call: {:?}",
							result.error,
						)));
					};

					Default::default()
				} else {
					// Dry run the call.
					let result = crate::Pallet::<T>::bare_call(
						OriginFor::<T>::signed(origin),
						dest,
						value,
						transaction_limits,
						input.clone(),
						exec_config,
					);

					let data = match result.result {
						Ok(return_value) => {
							if return_value.did_revert() {
								return Err(EthTransactError::Data(return_value.data));
							}
							return_value.data
						},
						Err(err) => {
							log::debug!(target: LOG_TARGET, "Failed to execute call: {err:?}");
							return extract_error(err);
						},
					};

					EthTransactInfo {
						weight_required: result.weight_required,
						storage_deposit: result.storage_deposit.charge_or_zero(),
						max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
						data,
						eth_gas: Default::default(),
					}
				}
			},
			// A contract deployment
			None => {
				// Extract code and data from the input.
				let (code, data) = if input.starts_with(&polkavm_common::program::BLOB_MAGIC) {
					extract_code_and_data(&input).unwrap_or_else(|| (input, Default::default()))
				} else {
					(input, vec![])
				};

				// Dry run the call.
				let result = crate::Pallet::<T>::bare_instantiate(
					OriginFor::<T>::signed(origin),
					value,
					transaction_limits,
					Code::Upload(code.clone()),
					data.clone(),
					None,
					exec_config,
				);

				let returned_data = match result.result {
					Ok(return_value) => {
						if return_value.result.did_revert() {
							return Err(EthTransactError::Data(return_value.result.data));
						}
						return_value.result.data
					},
					Err(err) => {
						log::debug!(target: LOG_TARGET, "Failed to instantiate: {err:?}");
						return extract_error(err);
					},
				};

				EthTransactInfo {
					weight_required: result.weight_required,
					storage_deposit: result.storage_deposit.charge_or_zero(),
					max_storage_deposit: result.max_storage_deposit.charge_or_zero(),
					data: returned_data,
					eth_gas: Default::default(),
				}
			},
		};

		// replace the weight passed in the transaction with the dry_run result
		call_info.call.set_weight_limit(dry_run.weight_required);

		// we notify the wallet that the tx would not fit
		let total_weight = T::FeeInfo::dispatch_info(&call_info.call).total_weight();
		let max_weight = Self::evm_max_extrinsic_weight();
		if total_weight.any_gt(max_weight) {
			log::debug!(target: LOG_TARGET, "Transaction weight estimate exceeds extrinsic maximum: \
				total_weight={total_weight:?} \
				max_weight={max_weight:?}",
			);

			Err(EthTransactError::Message(format!(
				"\
				The transaction consumes more than the allowed weight. \
				needed={total_weight} \
				allowed={max_weight} \
				overweight_by={}\
				",
				total_weight.saturating_sub(max_weight),
			)))?;
		}

		// not enough gas supplied to pay for both the tx fees and the storage deposit
		let transaction_fee = T::FeeInfo::tx_fee(call_info.encoded_len, &call_info.call);
		let available_fee = T::FeeInfo::remaining_txfee();
		if transaction_fee > available_fee {
			Err(EthTransactError::Message(format!(
				"Not enough gas supplied: Off by: {:?}",
				transaction_fee.saturating_sub(available_fee),
			)))?;
		}

		let total_cost = transaction_fee.saturating_add(dry_run.max_storage_deposit);
		let total_cost_wei = Pallet::<T>::convert_native_to_evm(total_cost);
		let (mut eth_gas, rest) = total_cost_wei.div_mod(base_fee);
		if !rest.is_zero() {
			eth_gas = eth_gas.saturating_add(1_u32.into());
		}

		log::debug!(target: LOG_TARGET, "\
			dry_run_eth_transact finished: \
			weight_limit={}, \
			total_weight={total_weight}, \
			max_weight={max_weight}, \
			weight_left={}, \
			eth_gas={eth_gas}, \
			encoded_len={}, \
			tx_fee={transaction_fee:?}, \
			storage_deposit={:?}, \
			max_storage_deposit={:?}\
			",
			dry_run.weight_required,
			max_weight.saturating_sub(total_weight),
			call_info.encoded_len,
			dry_run.storage_deposit,
			dry_run.max_storage_deposit,

		);
		dry_run.eth_gas = eth_gas;
		Ok(dry_run)
	}

	/// Get the balance with EVM decimals of the given `address`.
	///
	/// Returns the spendable balance excluding the existential deposit.
	pub fn evm_balance(address: &H160) -> U256 {
		let balance = AccountInfo::<T>::balance_of((*address).into());
		Self::convert_native_to_evm(balance)
	}

	/// Get the current Ethereum block from storage.
	pub fn eth_block() -> EthBlock {
		EthereumBlock::<T>::get()
	}

	/// Convert the Ethereum block number into the Ethereum block hash.
	///
	/// # Note
	///
	/// The Ethereum block number is identical to the Substrate block number.
	/// If the provided block number is outside of the pruning None is returned.
	pub fn eth_block_hash_from_number(number: U256) -> Option<H256> {
		let number = BlockNumberFor::<T>::try_from(number).ok()?;
		let hash = <BlockHash<T>>::get(number);
		if hash == H256::zero() {
			None
		} else {
			Some(hash)
		}
	}

	/// The details needed to reconstruct the receipt information offchain.
	pub fn eth_receipt_data() -> Vec<ReceiptGasInfo> {
		ReceiptInfoData::<T>::get()
	}

	/// Set the EVM balance of an account.
	///
	/// The account's total balance becomes the EVM value plus the existential deposit,
	/// consistent with `evm_balance` which returns the spendable balance excluding the existential
	/// deposit.
	pub fn set_evm_balance(address: &H160, evm_value: U256) -> Result<(), Error<T>> {
		let (balance, dust) = Self::new_balance_with_dust(evm_value)
			.map_err(|_| <Error<T>>::BalanceConversionFailed)?;
		let account_id = T::AddressMapper::to_account_id(&address);
		T::Currency::set_balance(&account_id, balance);
		AccountInfoOf::<T>::mutate(&address, |account| {
			if let Some(account) = account {
				account.dust = dust;
			} else {
				*account = Some(AccountInfo { dust, ..Default::default() });
			}
		});

		Ok(())
	}

	/// Construct native balance from EVM balance.
	///
	/// Adds the existential deposit and returns the native balance plus the dust.
	pub fn new_balance_with_dust(
		evm_value: U256,
	) -> Result<(BalanceOf<T>, u32), BalanceConversionError> {
		let ed = T::Currency::minimum_balance();
		let balance_with_dust = BalanceWithDust::<BalanceOf<T>>::from_value::<T>(evm_value)?;
		let (value, dust) = balance_with_dust.deconstruct();

		Ok((ed.saturating_add(value), dust))
	}

	/// Get the nonce for the given `address`.
	pub fn evm_nonce(address: &H160) -> u32
	where
		T::Nonce: Into<u32>,
	{
		let account = T::AddressMapper::to_account_id(&address);
		System::<T>::account_nonce(account).into()
	}

	/// Get the block gas limit.
	pub fn evm_block_gas_limit() -> U256 {
		// We just return `u64::MAX` because the gas cost of a transaction can get very large when
		// the transaction executes many storage deposits (in theory a contract can behave like a
		// factory, procedurally create code and make contract creation calls to store that as
		// code). It is too brittle to estimate a maximally possible amount here.
		// On the other hand, the data type `u64` seems to be the "common denominator" as the
		// typical data type tools and Ethereum implementations use to represent gas amounts.
		u64::MAX.into()
	}

	/// The maximum weight an `eth_transact` is allowed to consume.
	pub fn evm_max_extrinsic_weight() -> Weight {
		let factor = <T as Config>::MaxEthExtrinsicWeight::get();
		let max_weight = <T as frame_system::Config>::BlockWeights::get()
			.get(DispatchClass::Normal)
			.max_extrinsic
			.unwrap_or_else(|| <T as frame_system::Config>::BlockWeights::get().max_block);
		Weight::from_parts(
			factor.saturating_mul_int(max_weight.ref_time()),
			factor.saturating_mul_int(max_weight.proof_size()),
		)
	}

	/// Get the base gas price.
	pub fn evm_base_fee() -> U256 {
		let gas_scale = <T as Config>::GasScale::get();
		let multiplier = T::FeeInfo::next_fee_multiplier();
		multiplier
			.saturating_mul_int::<u128>(T::NativeToEthRatio::get().into())
			.saturating_mul(gas_scale.saturated_into())
			.into()
	}

	/// Build an EVM tracer from the given tracer type.
	pub fn evm_tracer(tracer_type: TracerType) -> Tracer<T>
	where
		T::Nonce: Into<u32>,
	{
		match tracer_type {
			TracerType::CallTracer(config) => CallTracer::new(config.unwrap_or_default()).into(),
			TracerType::PrestateTracer(config) =>
				PrestateTracer::new(config.unwrap_or_default()).into(),
		}
	}

	/// A generalized version of [`Self::upload_code`].
	///
	/// It is identical to [`Self::upload_code`] and only differs in the information it returns.
	pub fn bare_upload_code(
		origin: OriginFor<T>,
		code: Vec<u8>,
		storage_deposit_limit: BalanceOf<T>,
	) -> CodeUploadResult<BalanceOf<T>> {
		let origin = T::UploadOrigin::ensure_origin(origin)?;

		let bytecode_type = if code.starts_with(&polkavm_common::program::BLOB_MAGIC) {
			BytecodeType::Pvm
		} else {
			if !T::AllowEVMBytecode::get() {
				return Err(<Error<T>>::CodeRejected.into())
			}
			BytecodeType::Evm
		};

		let mut meter = TransactionMeter::new(TransactionLimits::WeightAndDeposit {
			weight_limit: Default::default(),
			deposit_limit: storage_deposit_limit,
		})?;

		let module = Self::try_upload_code(
			origin,
			code,
			bytecode_type,
			&mut meter,
			&ExecConfig::new_substrate_tx(),
		)?;
		Ok(CodeUploadReturnValue {
			code_hash: *module.code_hash(),
			deposit: meter.deposit_consumed().charge_or_zero(),
		})
	}

	/// Query storage of a specified contract under a specified key.
	pub fn get_storage(address: H160, key: [u8; 32]) -> GetStorageResult {
		let contract_info =
			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;

		let maybe_value = contract_info.read(&Key::from_fixed(key));
		Ok(maybe_value)
	}

	/// Get the immutable data of a specified contract.
	///
	/// Returns `None` if the contract does not exist or has no immutable data.
	pub fn get_immutables(address: H160) -> Option<ImmutableData> {
		let immutable_data = <ImmutableDataOf<T>>::get(address);
		immutable_data
	}

	/// Sets immutable data of a contract
	///
	/// Returns an error if the contract does not exist.
	///
	/// # Warning
	///
	/// Does not collect any storage deposit. Not safe to be called by user controlled code.
	pub fn set_immutables(address: H160, data: ImmutableData) -> Result<(), ContractAccessError> {
		AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;
		<ImmutableDataOf<T>>::insert(address, data);
		Ok(())
	}

	/// Query storage of a specified contract under a specified variable-sized key.
	pub fn get_storage_var_key(address: H160, key: Vec<u8>) -> GetStorageResult {
		let contract_info =
			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;

		let maybe_value = contract_info.read(
			&Key::try_from_var(key)
				.map_err(|_| ContractAccessError::KeyDecodingFailed)?
				.into(),
		);
		Ok(maybe_value)
	}

	/// Convert a native balance to EVM balance.
	pub fn convert_native_to_evm(value: impl Into<BalanceWithDust<BalanceOf<T>>>) -> U256 {
		let (value, dust) = value.into().deconstruct();
		value
			.into()
			.saturating_mul(T::NativeToEthRatio::get().into())
			.saturating_add(dust.into())
	}

	/// Set storage of a specified contract under a specified key.
	///
	/// If the `value` is `None`, the storage entry is deleted.
	///
	/// Returns an error if the contract does not exist or if the write operation fails.
	///
	/// # Warning
	///
	/// Does not collect any storage deposit. Not safe to be called by user controlled code.
	pub fn set_storage(address: H160, key: [u8; 32], value: Option<Vec<u8>>) -> SetStorageResult {
		let contract_info =
			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;

		contract_info
			.write(&Key::from_fixed(key), value, None, false)
			.map_err(ContractAccessError::StorageWriteFailed)
	}

	/// Set the storage of a specified contract under a specified variable-sized key.
	///
	/// If the `value` is `None`, the storage entry is deleted.
	///
	/// Returns an error if the contract does not exist, if the key decoding fails,
	/// or if the write operation fails.
	///
	/// # Warning
	///
	/// Does not collect any storage deposit. Not safe to be called by user controlled code.
	pub fn set_storage_var_key(
		address: H160,
		key: Vec<u8>,
		value: Option<Vec<u8>>,
	) -> SetStorageResult {
		let contract_info =
			AccountInfo::<T>::load_contract(&address).ok_or(ContractAccessError::DoesntExist)?;

		contract_info
			.write(
				&Key::try_from_var(key)
					.map_err(|_| ContractAccessError::KeyDecodingFailed)?
					.into(),
				value,
				None,
				false,
			)
			.map_err(ContractAccessError::StorageWriteFailed)
	}

	/// Pallet account, used to hold funds for contracts upload deposit.
	pub fn account_id() -> T::AccountId {
		use frame_support::PalletId;
		use sp_runtime::traits::AccountIdConversion;
		PalletId(*b"py/reviv").into_account_truncating()
	}

	/// The address of the validator that produced the current block.
	pub fn block_author() -> H160 {
		use frame_support::traits::FindAuthor;

		let digest = <frame_system::Pallet<T>>::digest();
		let pre_runtime_digests = digest.logs.iter().filter_map(|d| d.as_pre_runtime());

		T::FindAuthor::find_author(pre_runtime_digests)
			.map(|account_id| T::AddressMapper::to_address(&account_id))
			.unwrap_or_default()
	}

	/// Returns the code at `address`.
	///
	/// This takes pre-compiles into account.
	pub fn code(address: &H160) -> Vec<u8> {
		use precompiles::{All, Precompiles};
		if let Some(code) = <All<T>>::code(address.as_fixed_bytes()) {
			return code.into()
		}
		AccountInfo::<T>::load_contract(&address)
			.and_then(|contract| <PristineCode<T>>::get(contract.code_hash))
			.map(|code| code.into())
			.unwrap_or_default()
	}

	/// Uploads new code and returns the Vm binary contract blob and deposit amount collected.
	pub fn try_upload_code(
		origin: T::AccountId,
		code: Vec<u8>,
		code_type: BytecodeType,
		meter: &mut TransactionMeter<T>,
		exec_config: &ExecConfig<T>,
	) -> Result<ContractBlob<T>, DispatchError> {
		let mut module = match code_type {
			BytecodeType::Pvm => ContractBlob::from_pvm_code(code, origin)?,
			BytecodeType::Evm => ContractBlob::from_evm_runtime_code(code, origin)?,
		};
		module.store_code(exec_config, meter)?;
		Ok(module)
	}

	/// Run the supplied function `f` if no other instance of this pallet is on the stack.
	fn run_guarded<R, F: FnOnce() -> Result<R, ExecError>>(f: F) -> Result<R, ExecError> {
		executing_contract::using_once(&mut false, || {
			executing_contract::with(|f| {
				// Fail if already entered contract execution
				if *f {
					return Err(())
				}
				// We are entering contract execution
				*f = true;
				Ok(())
			})
				.expect("Returns `Ok` if called within `using_once`. It is syntactically obvious that this is the case; qed")
				.map_err(|_| <Error<T>>::ReenteredPallet.into())
				.map(|_| f())
				.and_then(|r| r)
		})
	}

	/// Transfer a deposit from some account to another.
	///
	/// `from` is usually the transaction origin and `to` a contract or
	/// the pallets own account.
	fn charge_deposit(
		hold_reason: Option<HoldReason>,
		from: &T::AccountId,
		to: &T::AccountId,
		amount: BalanceOf<T>,
		exec_config: &ExecConfig<T>,
	) -> DispatchResult {
		use frame_support::traits::tokens::{Fortitude, Precision, Preservation};

		if amount.is_zero() {
			return Ok(());
		}

		match (exec_config.collect_deposit_from_hold.is_some(), hold_reason) {
			(true, hold_reason) => {
				T::FeeInfo::withdraw_txfee(amount)
					.ok_or(())
					.and_then(|credit| T::Currency::resolve(to, credit).map_err(|_| ()))
					.and_then(|_| {
						if let Some(hold_reason) = hold_reason {
							T::Currency::hold(&hold_reason.into(), to, amount).map_err(|_| ())?;
						}
						Ok(())
					})
					.map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
			},
			(false, Some(hold_reason)) => {
				T::Currency::transfer_and_hold(
					&hold_reason.into(),
					from,
					to,
					amount,
					Precision::Exact,
					Preservation::Preserve,
					Fortitude::Polite,
				)
				.map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
			},
			(false, None) => {
				T::Currency::transfer(from, to, amount, Preservation::Preserve)
					.map_err(|_| Error::<T>::StorageDepositNotEnoughFunds)?;
			},
		}
		Ok(())
	}

	/// Refund a deposit.
	///
	/// `to` is usually the transaction origin and `from` a contract or
	/// the pallets own account.
	fn refund_deposit(
		hold_reason: HoldReason,
		from: &T::AccountId,
		to: &T::AccountId,
		amount: BalanceOf<T>,
		exec_config: Option<&ExecConfig<T>>,
	) -> Result<(), DispatchError> {
		use frame_support::traits::{
			fungible::InspectHold,
			tokens::{Fortitude, Precision, Preservation, Restriction},
		};

		if amount.is_zero() {
			return Ok(());
		}

		let hold_reason = hold_reason.into();
		let result = if exec_config.map(|c| c.collect_deposit_from_hold.is_some()).unwrap_or(false)
		{
			T::Currency::release(&hold_reason, from, amount, Precision::Exact)
				.and_then(|amount| {
					T::Currency::withdraw(
						from,
						amount,
						Precision::Exact,
						Preservation::Preserve,
						Fortitude::Polite,
					)
				})
				.map(T::FeeInfo::deposit_txfee)
		} else {
			T::Currency::transfer_on_hold(
				&hold_reason,
				from,
				to,
				amount,
				Precision::Exact,
				Restriction::Free,
				Fortitude::Polite,
			)
			.map(|_| ())
		};

		result.map_err(|_| {
			let available = T::Currency::balance_on_hold(&hold_reason, from);
			if available < amount {
				// The storage deposit accounting got out of sync with the balance: This would be a
				// straight up bug in this pallet.
				log::error!(
					target: LOG_TARGET,
					"Failed to refund storage deposit {:?} from contract {:?} to origin {:?}. Not enough deposit: {:?}. This is a bug.",
					amount, from, to, available,
				);
				Error::<T>::StorageRefundNotEnoughFunds.into()
			} else {
				// There are some locks preventing the refund. This could be the case if the
				// contract participates in government. The consequence is that if a contract votes
				// with its storage deposit it would no longer be possible to remove storage without first
				// reducing the lock.
				log::warn!(
					target: LOG_TARGET,
					"Failed to refund storage deposit {:?} from contract {:?} to origin {:?}. First remove locks (staking, governance) from the contracts account.",
					amount, from, to,
				);
				Error::<T>::StorageRefundLocked.into()
			}
		})
	}

	/// Returns true if the evm value carries dust.
	fn has_dust(value: U256) -> bool {
		value % U256::from(<T>::NativeToEthRatio::get()) != U256::zero()
	}

	/// Returns true if the evm value carries balance.
	fn has_balance(value: U256) -> bool {
		value >= U256::from(<T>::NativeToEthRatio::get())
	}

	/// Return the existential deposit of [`Config::Currency`].
	fn min_balance() -> BalanceOf<T> {
		<T::Currency as Inspect<AccountIdOf<T>>>::minimum_balance()
	}

	/// Deposit a pallet revive event.
	///
	/// This method will be called by the EVM to deposit events emitted by the contract.
	/// Therefore all events must be contract emitted events.
	fn deposit_event(event: Event<T>) {
		<frame_system::Pallet<T>>::deposit_event(<T as Config>::RuntimeEvent::from(event))
	}

	// Returns Ok with the account that signed the eth transaction.
	fn ensure_eth_signed(origin: OriginFor<T>) -> Result<AccountIdOf<T>, DispatchError> {
		match <T as Config>::RuntimeOrigin::from(origin).into() {
			Ok(Origin::EthTransaction(signer)) => Ok(signer),
			_ => Err(BadOrigin.into()),
		}
	}

	/// Ensure that the origin is neither a pre-compile nor a contract.
	///
	/// This enforces EIP-3607.
	fn ensure_non_contract_if_signed(origin: &OriginFor<T>) -> DispatchResult {
		if DebugSettings::bypass_eip_3607::<T>() {
			return Ok(())
		}
		let Some(address) = origin
			.as_system_ref()
			.and_then(|o| o.as_signed())
			.map(<T::AddressMapper as AddressMapper<T>>::to_address)
		else {
			return Ok(())
		};
		if exec::is_precompile::<T, ContractBlob<T>>(&address) ||
			<AccountInfo<T>>::is_contract(&address)
		{
			log::debug!(
				target: crate::LOG_TARGET,
				"EIP-3607: reject tx as pre-compile or account exist at {address:?}",
			);
			Err(DispatchError::BadOrigin)
		} else {
			Ok(())
		}
	}
}

/// The address used to call the runtime's pallets dispatchables
///
/// Note:
/// computed with PalletId(*b"py/paddr").into_account_truncating();
pub const RUNTIME_PALLETS_ADDR: H160 =
	H160(hex_literal::hex!("6d6f646c70792f70616464720000000000000000"));

// Set up a global reference to the boolean flag used for the re-entrancy guard.
environmental!(executing_contract: bool);

sp_api::decl_runtime_apis! {
	/// The API used to dry-run contract interactions.
	#[api_version(1)]
	pub trait ReviveApi<AccountId, Balance, Nonce, BlockNumber, Moment> where
		AccountId: Codec,
		Balance: Codec,
		Nonce: Codec,
		BlockNumber: Codec,
		Moment: Codec,
	{
		/// Returns the current ETH block.
		///
		/// This is one block behind the substrate block.
		fn eth_block() -> EthBlock;

		/// Returns the ETH block hash for the given block number.
		fn eth_block_hash(number: U256) -> Option<H256>;

		/// The details needed to reconstruct the receipt information offchain.
		///
		/// # Note
		///
		/// Each entry corresponds to the appropriate Ethereum transaction in the current block.
		fn eth_receipt_data() -> Vec<ReceiptGasInfo>;

		/// Returns the block gas limit.
		fn block_gas_limit() -> U256;

		/// Returns the free balance of the given `[H160]` address, using EVM decimals.
		fn balance(address: H160) -> U256;

		/// Returns the gas price.
		fn gas_price() -> U256;

		/// Returns the nonce of the given `[H160]` address.
		fn nonce(address: H160) -> Nonce;

		/// Perform a call from a specified account to a given contract.
		///
		/// See [`crate::Pallet::bare_call`].
		fn call(
			origin: AccountId,
			dest: H160,
			value: Balance,
			gas_limit: Option<Weight>,
			storage_deposit_limit: Option<Balance>,
			input_data: Vec<u8>,
		) -> ContractResult<ExecReturnValue, Balance>;

		/// Instantiate a new contract.
		///
		/// See `[crate::Pallet::bare_instantiate]`.
		fn instantiate(
			origin: AccountId,
			value: Balance,
			gas_limit: Option<Weight>,
			storage_deposit_limit: Option<Balance>,
			code: Code,
			data: Vec<u8>,
			salt: Option<[u8; 32]>,
		) -> ContractResult<InstantiateReturnValue, Balance>;


		/// Perform an Ethereum call.
		///
		/// Deprecated use `v2` version instead.
		/// See [`crate::Pallet::dry_run_eth_transact`]
		fn eth_transact(tx: GenericTransaction) -> Result<EthTransactInfo<Balance>, EthTransactError>;

		/// Perform an Ethereum call.
		///
		/// See [`crate::Pallet::dry_run_eth_transact`]
		fn eth_transact_with_config(
			tx: GenericTransaction,
			config: DryRunConfig<Moment>,
		) -> Result<EthTransactInfo<Balance>, EthTransactError>;

		/// Upload new code without instantiating a contract from it.
		///
		/// See [`crate::Pallet::bare_upload_code`].
		fn upload_code(
			origin: AccountId,
			code: Vec<u8>,
			storage_deposit_limit: Option<Balance>,
		) -> CodeUploadResult<Balance>;

		/// Query a given storage key in a given contract.
		///
		/// Returns `Ok(Some(Vec<u8>))` if the storage value exists under the given key in the
		/// specified account and `Ok(None)` if it doesn't. If the account specified by the address
		/// doesn't exist, or doesn't have a contract then `Err` is returned.
		fn get_storage(
			address: H160,
			key: [u8; 32],
		) -> GetStorageResult;

		/// Query a given variable-sized storage key in a given contract.
		///
		/// Returns `Ok(Some(Vec<u8>))` if the storage value exists under the given key in the
		/// specified account and `Ok(None)` if it doesn't. If the account specified by the address
		/// doesn't exist, or doesn't have a contract then `Err` is returned.
		fn get_storage_var_key(
			address: H160,
			key: Vec<u8>,
		) -> GetStorageResult;

		/// Traces the execution of an entire block and returns call traces.
		///
		/// This is intended to be called through `state_call` to replay the block from the
		/// parent block.
		///
		/// See eth-rpc `debug_traceBlockByNumber` for usage.
		fn trace_block(
			block: Block,
			config: TracerType
		) -> Vec<(u32, Trace)>;

		/// Traces the execution of a specific transaction within a block.
		///
		/// This is intended to be called through `state_call` to replay the block from the
		/// parent hash up to the transaction.
		///
		/// See eth-rpc `debug_traceTransaction` for usage.
		fn trace_tx(
			block: Block,
			tx_index: u32,
			config: TracerType
		) -> Option<Trace>;

		/// Dry run and return the trace of the given call.
		///
		/// See eth-rpc `debug_traceCall` for usage.
		fn trace_call(tx: GenericTransaction, config: TracerType) -> Result<Trace, EthTransactError>;

		/// The address of the validator that produced the current block.
		fn block_author() -> H160;

		/// Get the H160 address associated to this account id
		fn address(account_id: AccountId) -> H160;

		/// Get the account id associated to this H160 address.
		fn account_id(address: H160) -> AccountId;

		/// The address used to call the runtime's pallets dispatchables
		fn runtime_pallets_address() -> H160;

		/// The code at the specified address taking pre-compiles into account.
		fn code(address: H160) -> Vec<u8>;

		/// Construct the new balance and dust components of this EVM balance.
		fn new_balance_with_dust(balance: U256) -> Result<(Balance, u32), BalanceConversionError>;
	}
}

/// This macro wraps substrate's `impl_runtime_apis!` and implements `pallet_revive` runtime APIs
/// and other required traits.
///
/// # Note
///
/// This also implements [`SetWeightLimit`] for the runtime call.
///
/// # Parameters
/// - `$Runtime`: The runtime type to implement the APIs for.
/// - `$Revive`: The name under which revive is declared in `construct_runtime`.
/// - `$Executive`: The Executive type of the runtime.
/// - `$EthExtra`: Type for additional Ethereum runtime extension.
/// - `$($rest:tt)*`: Remaining input to be forwarded to the underlying `impl_runtime_apis!`.
#[macro_export]
macro_rules! impl_runtime_apis_plus_revive_traits {
	($Runtime: ty, $Revive: ident, $Executive: ty, $EthExtra: ty, $($rest:tt)*) => {

		type __ReviveMacroMoment = <<$Runtime as $crate::Config>::Time as $crate::Time>::Moment;

		impl $crate::evm::runtime::SetWeightLimit for RuntimeCall {
			fn set_weight_limit(&mut self, new_weight_limit: Weight) -> Weight {
				use $crate::pallet::Call as ReviveCall;
				match self {
					Self::$Revive(
						ReviveCall::eth_call{ weight_limit, .. } |
						ReviveCall::eth_instantiate_with_code{ weight_limit, .. }
					) => {
						let old = *weight_limit;
						*weight_limit = new_weight_limit;
						old
					},
					_ => Weight::default(),
				}
			}
		}

		impl_runtime_apis! {
			$($rest)*


			impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, __ReviveMacroMoment> for $Runtime
			{
				fn eth_block() -> $crate::EthBlock {
					$crate::Pallet::<Self>::eth_block()
				}

				fn eth_block_hash(number: $crate::U256) -> Option<$crate::H256> {
					$crate::Pallet::<Self>::eth_block_hash_from_number(number)
				}

				fn eth_receipt_data() -> Vec<$crate::ReceiptGasInfo> {
					$crate::Pallet::<Self>::eth_receipt_data()
				}

				fn balance(address: $crate::H160) -> $crate::U256 {
					$crate::Pallet::<Self>::evm_balance(&address)
				}

				fn block_author() -> $crate::H160 {
					$crate::Pallet::<Self>::block_author()
				}

				fn block_gas_limit() -> $crate::U256 {
					$crate::Pallet::<Self>::evm_block_gas_limit()
				}

				fn gas_price() -> $crate::U256 {
					$crate::Pallet::<Self>::evm_base_fee()
				}

				fn nonce(address: $crate::H160) -> Nonce {
					use $crate::AddressMapper;
					let account = <Self as $crate::Config>::AddressMapper::to_account_id(&address);
					$crate::frame_system::Pallet::<Self>::account_nonce(account)
				}

				fn address(account_id: AccountId) -> $crate::H160 {
					use $crate::AddressMapper;
					<Self as $crate::Config>::AddressMapper::to_address(&account_id)
				}

				fn eth_transact(
					tx: $crate::evm::GenericTransaction,
				) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
					use $crate::{
						codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
						sp_runtime::traits::TransactionExtension,
						sp_runtime::traits::Block as BlockT
					};
					$crate::Pallet::<Self>::dry_run_eth_transact(tx, Default::default())
				}

				fn eth_transact_with_config(
					tx: $crate::evm::GenericTransaction,
					config: $crate::DryRunConfig<__ReviveMacroMoment>,
				) -> Result<$crate::EthTransactInfo<Balance>, $crate::EthTransactError> {
					use $crate::{
						codec::Encode, evm::runtime::EthExtra, frame_support::traits::Get,
						sp_runtime::traits::TransactionExtension,
						sp_runtime::traits::Block as BlockT
					};
					$crate::Pallet::<Self>::dry_run_eth_transact(tx, config)
				}

				fn call(
					origin: AccountId,
					dest: $crate::H160,
					value: Balance,
					weight_limit: Option<$crate::Weight>,
					storage_deposit_limit: Option<Balance>,
					input_data: Vec<u8>,
				) -> $crate::ContractResult<$crate::ExecReturnValue, Balance> {
					use $crate::frame_support::traits::Get;
					let blockweights: $crate::BlockWeights =
						<Self as $crate::frame_system::Config>::BlockWeights::get();

					$crate::Pallet::<Self>::prepare_dry_run(&origin);
					$crate::Pallet::<Self>::bare_call(
						<Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
						dest,
						$crate::Pallet::<Self>::convert_native_to_evm(value),
						$crate::TransactionLimits::WeightAndDeposit {
							weight_limit: weight_limit.unwrap_or(blockweights.max_block),
							deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
						},
						input_data,
						$crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
					)
				}

				fn instantiate(
					origin: AccountId,
					value: Balance,
					weight_limit: Option<$crate::Weight>,
					storage_deposit_limit: Option<Balance>,
					code: $crate::Code,
					data: Vec<u8>,
					salt: Option<[u8; 32]>,
				) -> $crate::ContractResult<$crate::InstantiateReturnValue, Balance> {
					use $crate::frame_support::traits::Get;
					let blockweights: $crate::BlockWeights =
						<Self as $crate::frame_system::Config>::BlockWeights::get();

					$crate::Pallet::<Self>::prepare_dry_run(&origin);
					$crate::Pallet::<Self>::bare_instantiate(
						<Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin),
						$crate::Pallet::<Self>::convert_native_to_evm(value),
						$crate::TransactionLimits::WeightAndDeposit {
							weight_limit: weight_limit.unwrap_or(blockweights.max_block),
							deposit_limit: storage_deposit_limit.unwrap_or(u128::MAX),
						},
						code,
						data,
						salt,
						$crate::ExecConfig::new_substrate_tx().with_dry_run(Default::default()),
					)
				}

				fn upload_code(
					origin: AccountId,
					code: Vec<u8>,
					storage_deposit_limit: Option<Balance>,
				) -> $crate::CodeUploadResult<Balance> {
					let origin =
						<Self as $crate::frame_system::Config>::RuntimeOrigin::signed(origin);
					$crate::Pallet::<Self>::bare_upload_code(
						origin,
						code,
						storage_deposit_limit.unwrap_or(u128::MAX),
					)
				}

				fn get_storage_var_key(
					address: $crate::H160,
					key: Vec<u8>,
				) -> $crate::GetStorageResult {
					$crate::Pallet::<Self>::get_storage_var_key(address, key)
				}

				fn get_storage(address: $crate::H160, key: [u8; 32]) -> $crate::GetStorageResult {
					$crate::Pallet::<Self>::get_storage(address, key)
				}

				fn trace_block(
					block: Block,
					tracer_type: $crate::evm::TracerType,
				) -> Vec<(u32, $crate::evm::Trace)> {
					use $crate::{sp_runtime::traits::Block, tracing::trace};
					let mut traces = vec![];
					let (header, extrinsics) = block.deconstruct();
					<$Executive>::initialize_block(&header);
					for (index, ext) in extrinsics.into_iter().enumerate() {
						let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type.clone());
						let t = tracer.as_tracing();
						let _ = trace(t, || <$Executive>::apply_extrinsic(ext));

						if let Some(tx_trace) = tracer.collect_trace() {
							traces.push((index as u32, tx_trace));
						}
					}

					traces
				}

				fn trace_tx(
					block: Block,
					tx_index: u32,
					tracer_type: $crate::evm::TracerType,
				) -> Option<$crate::evm::Trace> {
					use $crate::{sp_runtime::traits::Block, tracing::trace};

					let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type);
					let (header, extrinsics) = block.deconstruct();

					<$Executive>::initialize_block(&header);
					for (index, ext) in extrinsics.into_iter().enumerate() {
						if index as u32 == tx_index {
							let t = tracer.as_tracing();
							let _ = trace(t, || <$Executive>::apply_extrinsic(ext));
							break;
						} else {
							let _ = <$Executive>::apply_extrinsic(ext);
						}
					}

					tracer.collect_trace()
				}

				fn trace_call(
					tx: $crate::evm::GenericTransaction,
					tracer_type: $crate::evm::TracerType,
				) -> Result<$crate::evm::Trace, $crate::EthTransactError> {
					use $crate::tracing::trace;
					let mut tracer = $crate::Pallet::<Self>::evm_tracer(tracer_type.clone());
					let t = tracer.as_tracing();

					t.watch_address(&tx.from.unwrap_or_default());
					t.watch_address(&$crate::Pallet::<Self>::block_author());
					let result = trace(t, || Self::eth_transact(tx));

					if let Some(trace) = tracer.collect_trace() {
						Ok(trace)
					} else if let Err(err) = result {
						Err(err)
					} else {
						Ok($crate::Pallet::<Self>::evm_tracer(tracer_type).empty_trace())
					}
				}

				fn runtime_pallets_address() -> $crate::H160 {
					$crate::RUNTIME_PALLETS_ADDR
				}

				fn code(address: $crate::H160) -> Vec<u8> {
					$crate::Pallet::<Self>::code(&address)
				}

				fn account_id(address: $crate::H160) -> AccountId {
					use $crate::AddressMapper;
					<Self as $crate::Config>::AddressMapper::to_account_id(&address)
				}

				fn new_balance_with_dust(balance: $crate::U256) -> Result<(Balance, u32), $crate::BalanceConversionError> {
					$crate::Pallet::<Self>::new_balance_with_dust(balance)
				}
			}
		}
	};
}