namada_vm 0.48.3

The Namada VM
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
//! Virtual machine's host environment exposes functions that may be called from
//! within a virtual machine.

use std::cell::RefCell;
use std::collections::BTreeSet;
use std::fmt::Debug;
use std::num::TryFromIntError;

use namada_account::AccountPublicKeysMap;
use namada_core::address::{self, Address, ESTABLISHED_ADDRESS_BYTES_LEN};
use namada_core::arith::checked;
use namada_core::borsh::{BorshDeserialize, BorshSerializeExt};
use namada_core::chain::BlockHeight;
use namada_core::collections::HashSet;
use namada_core::decode;
use namada_core::hash::Hash;
use namada_core::internal::{HostEnvResult, KeyVal};
use namada_core::storage::{Key, TxIndex, TX_INDEX_LENGTH};
use namada_events::{Event, EventTypeBuilder};
use namada_gas::{
    self as gas, Gas, GasMetering, TxGasMeter, VpGasMeter,
    MEMORY_ACCESS_GAS_PER_BYTE,
};
use namada_state::prefix_iter::{PrefixIteratorId, PrefixIterators};
use namada_state::write_log::{self, WriteLog};
use namada_state::{
    DBIter, InMemory, OptionExt, ResultExt, State, StateRead, StorageHasher,
    StorageRead, StorageWrite, TxHostEnvState, VpHostEnvState, DB,
};
pub use namada_state::{Error, Result};
use namada_token::storage_key::{
    is_any_minted_balance_key, is_any_minter_key, is_any_token_balance_key,
    is_any_token_parameter_key,
};
use namada_token::MaspTransaction;
use namada_tx::data::TxSentinel;
use namada_tx::{BatchedTx, BatchedTxRef, Tx, TxCommitments};
use namada_vp::vp_host_fns;
use thiserror::Error;

#[cfg(feature = "wasm-runtime")]
use super::wasm::{TxCache, VpCache};
use crate::memory::VmMemory;
use crate::{
    HostRef, RoAccess, RoHostRef, RwAccess, RwHostRef, WasmCacheAccess,
};

/// These runtime errors will abort tx WASM execution immediately
#[allow(missing_docs)]
#[allow(clippy::result_large_err)]
#[derive(Error, Debug)]
pub enum TxRuntimeError {
    #[error("Out of gas: {0}")]
    OutOfGas(gas::Error),
    #[error("Gas overflow")]
    GasOverflow,
    #[error("Trying to modify storage for an address that doesn't exit {0}")]
    UnknownAddressStorageModification(Address),
    #[error(
        "Trying to use a validity predicate with an invalid WASM code hash {0}"
    )]
    InvalidVpCodeHash(String),
    #[error("A validity predicate of an account cannot be deleted")]
    CannotDeleteVp,
    #[error("Encoding error: {0}")]
    EncodingError(std::io::Error),
    #[error("Address error: {0}")]
    AddressError(address::DecodeError),
    #[error("Numeric conversion error: {0}")]
    NumConversionError(#[from] TryFromIntError),
    #[error("Memory error: {0}")]
    MemoryError(Box<dyn std::error::Error + Sync + Send + 'static>),
    #[error("No value found in result buffer")]
    NoValueInResultBuffer,
    #[error("VP code is not allowed in allowlist parameter.")]
    DisallowedVp,
}

impl From<TxRuntimeError> for namada_state::Error {
    fn from(value: TxRuntimeError) -> Self {
        Self::new(value)
    }
}

/// Result of a tx host env fn call
pub type TxResult<T> = namada_state::Result<T>;

/// A transaction's host environment
pub struct TxVmEnv<MEM, D, H, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
{
    /// The VM memory for bi-directional data passing
    pub memory: MEM,
    /// The tx context contains references to host structures.
    pub ctx: TxCtx<D, H, CA>,
}

/// A transaction's host context
#[derive(Debug)]
pub struct TxCtx<D, H, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
{
    /// Mutable access to write log.
    pub write_log: HostRef<RwAccess, WriteLog>,
    /// Read-only access to in-memory state.
    pub in_mem: HostRef<RoAccess, InMemory<H>>,
    /// Read-only access to DB.
    pub db: HostRef<RoAccess, D>,
    /// Storage prefix iterators.
    pub iterators: HostRef<RwAccess, PrefixIterators<'static, D>>,
    /// Transaction gas meter. In  `RefCell` to charge gas in read-only fns.
    pub gas_meter: HostRef<RoAccess, RefCell<TxGasMeter>>,
    /// Transaction sentinel. In  `RefCell` to charge gas in read-only fns.
    pub sentinel: HostRef<RoAccess, RefCell<TxSentinel>>,
    /// The transaction code is used for signature verification
    pub tx: HostRef<RoAccess, Tx>,
    /// The commitments inside the transaction
    pub cmt: HostRef<RoAccess, TxCommitments>,
    /// The transaction index is used to identify a shielded transaction's
    /// parent
    pub tx_index: HostRef<RoAccess, TxIndex>,
    /// The verifiers whose validity predicates should be triggered.
    pub verifiers: HostRef<RwAccess, BTreeSet<Address>>,
    /// Cache for 2-step reads from host environment.
    pub result_buffer: HostRef<RwAccess, Option<Vec<u8>>>,
    /// Storage for byte buffer values yielded from the guest.
    pub yielded_value: HostRef<RwAccess, Option<Vec<u8>>>,
    /// VP WASM compilation cache (this is available in tx context, because
    /// we're pre-compiling VPs from [`tx_init_account`])
    #[cfg(feature = "wasm-runtime")]
    pub vp_wasm_cache: HostRef<RwAccess, VpCache<CA>>,
    /// Tx WASM compilation cache
    #[cfg(feature = "wasm-runtime")]
    pub tx_wasm_cache: HostRef<RwAccess, TxCache<CA>>,
    /// To avoid unused parameter without "wasm-runtime" feature
    #[cfg(not(feature = "wasm-runtime"))]
    pub cache_access: std::marker::PhantomData<CA>,
}

impl<MEM, D, H, CA> TxVmEnv<MEM, D, H, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    CA: WasmCacheAccess,
{
    /// Create a new environment for transaction execution.
    ///
    /// # Safety
    ///
    /// The way the arguments to this function are used is not thread-safe,
    /// we're assuming single-threaded tx execution with exclusive access to the
    /// mutable references.
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        memory: MEM,
        write_log: &mut WriteLog,
        in_mem: &InMemory<H>,
        db: &D,
        iterators: &mut PrefixIterators<'static, D>,
        gas_meter: &RefCell<TxGasMeter>,
        sentinel: &RefCell<TxSentinel>,
        tx: &Tx,
        cmt: &TxCommitments,
        tx_index: &TxIndex,
        verifiers: &mut BTreeSet<Address>,
        result_buffer: &mut Option<Vec<u8>>,
        yielded_value: &mut Option<Vec<u8>>,
        #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache<CA>,
        #[cfg(feature = "wasm-runtime")] tx_wasm_cache: &mut TxCache<CA>,
    ) -> Self {
        let write_log = unsafe { RwHostRef::new(write_log) };
        let in_mem = unsafe { RoHostRef::new(in_mem) };
        let db = unsafe { RoHostRef::new(db) };
        let iterators = unsafe { RwHostRef::new(iterators) };
        let gas_meter = unsafe { RoHostRef::new(gas_meter) };
        let sentinel = unsafe { RoHostRef::new(sentinel) };
        let tx = unsafe { RoHostRef::new(tx) };
        let cmt = unsafe { RoHostRef::new(cmt) };
        let tx_index = unsafe { RoHostRef::new(tx_index) };
        let verifiers = unsafe { RwHostRef::new(verifiers) };
        let result_buffer = unsafe { RwHostRef::new(result_buffer) };
        let yielded_value = unsafe { RwHostRef::new(yielded_value) };
        #[cfg(feature = "wasm-runtime")]
        let vp_wasm_cache = unsafe { RwHostRef::new(vp_wasm_cache) };
        #[cfg(feature = "wasm-runtime")]
        let tx_wasm_cache = unsafe { RwHostRef::new(tx_wasm_cache) };
        let ctx = TxCtx {
            write_log,
            db,
            in_mem,
            iterators,
            gas_meter,
            sentinel,
            tx,
            cmt,
            tx_index,
            verifiers,
            result_buffer,
            yielded_value,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache,
            #[cfg(feature = "wasm-runtime")]
            tx_wasm_cache,
            #[cfg(not(feature = "wasm-runtime"))]
            cache_access: std::marker::PhantomData,
        };

        Self { memory, ctx }
    }

    /// Access state from within a tx
    pub fn state(&self) -> TxHostEnvState<'_, D, H> {
        self.ctx.state()
    }
}

impl<MEM, D, H, CA> Clone for TxVmEnv<MEM, D, H, CA>
where
    MEM: Clone,
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    CA: WasmCacheAccess,
{
    fn clone(&self) -> Self {
        Self {
            memory: self.memory.clone(),
            ctx: self.ctx.clone(),
        }
    }
}

impl<D, H, CA> TxCtx<D, H, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    CA: WasmCacheAccess,
{
    /// Access state from within a tx
    pub fn state(&self) -> TxHostEnvState<'_, D, H> {
        let write_log = unsafe { self.write_log.get_mut() };
        let db = unsafe { self.db.get() };
        let in_mem = unsafe { self.in_mem.get() };
        let gas_meter = unsafe { self.gas_meter.get() };
        let sentinel = unsafe { self.sentinel.get() };
        TxHostEnvState {
            write_log,
            db,
            in_mem,
            gas_meter,
            sentinel,
        }
    }

    /// Use gas meter and sentinel
    pub fn gas_meter_and_sentinel(
        &self,
    ) -> (&RefCell<TxGasMeter>, &RefCell<TxSentinel>) {
        let gas_meter = unsafe { self.gas_meter.get() };
        let sentinel = unsafe { self.sentinel.get() };
        (gas_meter, sentinel)
    }
}

impl<D, H, CA> Clone for TxCtx<D, H, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    CA: WasmCacheAccess,
{
    fn clone(&self) -> Self {
        Self {
            write_log: self.write_log,
            db: self.db,
            in_mem: self.in_mem,
            iterators: self.iterators,
            gas_meter: self.gas_meter,
            sentinel: self.sentinel,
            tx: self.tx,
            cmt: self.cmt,
            tx_index: self.tx_index,
            verifiers: self.verifiers,
            result_buffer: self.result_buffer,
            yielded_value: self.yielded_value,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache: self.vp_wasm_cache,
            #[cfg(feature = "wasm-runtime")]
            tx_wasm_cache: self.tx_wasm_cache,
            #[cfg(not(feature = "wasm-runtime"))]
            cache_access: std::marker::PhantomData,
        }
    }
}

/// A validity predicate's host environment
pub struct VpVmEnv<MEM, D, H, EVAL, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
{
    /// The VM memory for bi-directional data passing
    pub memory: MEM,
    /// The VP context contains references to host structures.
    pub ctx: VpCtx<D, H, EVAL, CA>,
}

/// A validity predicate's host context
pub struct VpCtx<D, H, EVAL, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
{
    /// The address of the account that owns the VP
    pub address: HostRef<RoAccess, Address>,
    /// Read-only access to write log.
    pub write_log: HostRef<RoAccess, WriteLog>,
    /// Read-only access to in-memory state.
    pub in_mem: HostRef<RoAccess, InMemory<H>>,
    /// Read-only access to DB.
    pub db: HostRef<RoAccess, D>,
    /// Storage prefix iterators.
    pub iterators: HostRef<RwAccess, PrefixIterators<'static, D>>,
    /// VP gas meter. In  `RefCell` to charge gas in read-only fns.
    pub gas_meter: HostRef<RoAccess, RefCell<VpGasMeter>>,
    /// The transaction code is used for signature verification
    pub tx: HostRef<RoAccess, Tx>,
    /// The commitments inside the transaction
    pub cmt: HostRef<RoAccess, TxCommitments>,
    /// The transaction index is used to identify a shielded transaction's
    /// parent
    pub tx_index: HostRef<RoAccess, TxIndex>,
    /// The runner of the [`vp_eval`] function
    pub eval_runner: HostRef<RoAccess, EVAL>,
    /// Cache for 2-step reads from host environment.
    pub result_buffer: HostRef<RwAccess, Option<Vec<u8>>>,
    /// Storage for byte buffer values yielded from the guest.
    pub yielded_value: HostRef<RwAccess, Option<Vec<u8>>>,
    /// The storage keys that have been changed. Used for calls to `eval`.
    pub keys_changed: HostRef<RoAccess, BTreeSet<Key>>,
    /// The verifiers whose validity predicates should be triggered. Used for
    /// calls to `eval`.
    pub verifiers: HostRef<RoAccess, BTreeSet<Address>>,
    /// VP WASM compilation cache
    #[cfg(feature = "wasm-runtime")]
    pub vp_wasm_cache: HostRef<RwAccess, VpCache<CA>>,
    /// To avoid unused parameter without "wasm-runtime" feature
    #[cfg(not(feature = "wasm-runtime"))]
    pub cache_access: std::marker::PhantomData<CA>,
}

/// A Validity predicate runner for calls from the [`vp_eval`] function.
pub trait VpEvaluator {
    /// DB type
    type Db: DB + for<'iter> DBIter<'iter>;
    /// Storage hasher type
    type H: StorageHasher;
    /// Recursive VP evaluator type
    type Eval: VpEvaluator;
    /// WASM compilation cache access
    type CA: WasmCacheAccess;

    /// Evaluate a given validity predicate code with the given input data.
    /// Currently, we can only evaluate VPs using WASM runner with WASM memory.
    ///
    /// Invariant: Calling `VpEvalRunner::eval` from the VP is synchronous as it
    /// shares mutable access to the host context with the VP.
    fn eval(
        &self,
        ctx: VpCtx<Self::Db, Self::H, Self::Eval, Self::CA>,
        vp_code_hash: Hash,
        input_data: BatchedTxRef<'_>,
    ) -> HostEnvResult;
}

impl<MEM, D, H, EVAL, CA> VpVmEnv<MEM, D, H, EVAL, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    /// Create a new environment for validity predicate execution.
    ///
    /// # Safety
    ///
    /// The way the arguments to this function are used is not thread-safe,
    /// we're assuming multi-threaded VP execution, but with with exclusive
    /// access to the mutable references (no shared access).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        memory: MEM,
        address: &Address,
        write_log: &WriteLog,
        in_mem: &InMemory<H>,
        db: &D,
        gas_meter: &RefCell<VpGasMeter>,
        tx: &Tx,
        cmt: &TxCommitments,
        tx_index: &TxIndex,
        iterators: &mut PrefixIterators<'static, D>,
        verifiers: &BTreeSet<Address>,
        result_buffer: &mut Option<Vec<u8>>,
        yielded_value: &mut Option<Vec<u8>>,
        keys_changed: &BTreeSet<Key>,
        eval_runner: &EVAL,
        #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache<CA>,
    ) -> Self {
        let ctx = VpCtx::new(
            address,
            write_log,
            in_mem,
            db,
            gas_meter,
            tx,
            cmt,
            tx_index,
            iterators,
            verifiers,
            result_buffer,
            yielded_value,
            keys_changed,
            eval_runner,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache,
        );

        Self { memory, ctx }
    }

    /// Access state from within a VP
    pub fn state(&self) -> VpHostEnvState<'_, D, H> {
        self.ctx.state()
    }
}

impl<MEM, D, H, EVAL, CA> Clone for VpVmEnv<MEM, D, H, EVAL, CA>
where
    MEM: Clone,
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    fn clone(&self) -> Self {
        Self {
            memory: self.memory.clone(),
            ctx: self.ctx.clone(),
        }
    }
}

impl<D, H, EVAL, CA> VpCtx<D, H, EVAL, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    /// Create a new context for validity predicate execution.
    ///
    /// # Safety
    ///
    /// The way the arguments to this function are used is not thread-safe,
    /// we're assuming multi-threaded VP execution, but with with exclusive
    /// access to the mutable references (no shared access).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        address: &Address,
        write_log: &WriteLog,
        in_mem: &InMemory<H>,
        db: &D,
        gas_meter: &RefCell<VpGasMeter>,
        tx: &Tx,
        cmt: &TxCommitments,
        tx_index: &TxIndex,
        iterators: &mut PrefixIterators<'static, D>,
        verifiers: &BTreeSet<Address>,
        result_buffer: &mut Option<Vec<u8>>,
        yielded_value: &mut Option<Vec<u8>>,
        keys_changed: &BTreeSet<Key>,
        eval_runner: &EVAL,
        #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache<CA>,
    ) -> Self {
        let address = unsafe { RoHostRef::new(address) };
        let write_log = unsafe { RoHostRef::new(write_log) };
        let db = unsafe { RoHostRef::new(db) };
        let in_mem = unsafe { RoHostRef::new(in_mem) };
        let tx = unsafe { RoHostRef::new(tx) };
        let cmt = unsafe { RoHostRef::new(cmt) };
        let tx_index = unsafe { RoHostRef::new(tx_index) };
        let iterators = unsafe { RwHostRef::new(iterators) };
        let gas_meter = unsafe { RoHostRef::new(gas_meter) };
        let verifiers = unsafe { RoHostRef::new(verifiers) };
        let result_buffer = unsafe { RwHostRef::new(result_buffer) };
        let yielded_value = unsafe { RwHostRef::new(yielded_value) };
        let keys_changed = unsafe { RoHostRef::new(keys_changed) };
        let eval_runner = unsafe { RoHostRef::new(eval_runner) };
        #[cfg(feature = "wasm-runtime")]
        let vp_wasm_cache = unsafe { RwHostRef::new(vp_wasm_cache) };
        Self {
            address,
            write_log,
            db,
            in_mem,
            iterators,
            gas_meter,
            tx,
            cmt,
            tx_index,
            eval_runner,
            result_buffer,
            yielded_value,
            keys_changed,
            verifiers,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache,
            #[cfg(not(feature = "wasm-runtime"))]
            cache_access: std::marker::PhantomData,
        }
    }

    /// Access state from within a VP
    pub fn state(&self) -> VpHostEnvState<'_, D, H> {
        let write_log = unsafe { self.write_log.get() };
        let db = unsafe { self.db.get() };
        let in_mem = unsafe { self.in_mem.get() };
        let gas_meter = unsafe { self.gas_meter.get() };
        VpHostEnvState {
            write_log,
            db,
            in_mem,
            gas_meter,
        }
    }

    /// Use gas meter
    pub fn gas_meter(&self) -> &RefCell<VpGasMeter> {
        let gas_meter = unsafe { self.gas_meter.get() };
        gas_meter
    }
}

impl<D, H, EVAL, CA> Clone for VpCtx<D, H, EVAL, CA>
where
    D: DB + for<'iter> DBIter<'iter>,
    H: StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    fn clone(&self) -> Self {
        Self {
            address: self.address,
            write_log: self.write_log,
            db: self.db,
            in_mem: self.in_mem,
            iterators: self.iterators,
            gas_meter: self.gas_meter,
            tx: self.tx,
            cmt: self.cmt,
            tx_index: self.tx_index,
            eval_runner: self.eval_runner,
            result_buffer: self.result_buffer,
            yielded_value: self.yielded_value,
            keys_changed: self.keys_changed,
            verifiers: self.verifiers,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache: self.vp_wasm_cache,
            #[cfg(not(feature = "wasm-runtime"))]
            cache_access: std::marker::PhantomData,
        }
    }
}

/// Add a gas cost incured in a transaction
pub fn tx_charge_gas<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    used_gas: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    consume_tx_gas(env, used_gas.into())
}

// Internal funtion to charge gas for txs. Called by the other functions in this
// file while the public version is left to be used directly from wasm and as a
// hook for gas instrumentation
fn consume_tx_gas<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    used_gas: Gas,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (gas_meter, sentinel) = env.ctx.gas_meter_and_sentinel();

    // if we run out of gas, we need to stop the execution
    gas_meter
        .borrow_mut()
        .consume(used_gas)
        .map_err(|err| {
            sentinel.borrow_mut().set_out_of_gas();
            tracing::info!(
                "Stopping transaction execution because of gas error: {}",
                err
            );

            TxRuntimeError::OutOfGas(err)
        })
        .into_storage_result()
}

/// Called from VP wasm to request to use the given gas amount
pub fn vp_charge_gas<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    used_gas: u64,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, used_gas.into())
}

/// Storage `has_key` function exposed to the wasm VM Tx environment. It will
/// try to check the write log first and if no entry found then the storage.
pub fn tx_has_key<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    key_ptr: u64,
    key_len: u64,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_has_key {}, key {}", key, key_ptr,);

    let key = Key::parse(key)?;

    // try to read from the write log first
    let state = env.state();
    let present = state.has_key(&key)?;
    Ok(HostEnvResult::from(present).to_i64())
}

/// Storage read function exposed to the wasm VM Tx environment. It will try to
/// read from the write log first and if no entry found then from the storage.
///
/// Returns `-1` when the key is not present, or the length of the data when
/// the key is present (the length may be `0`).
pub fn tx_read<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    key_ptr: u64,
    key_len: u64,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_read {}, key {}", key, key_ptr,);

    let key = Key::parse(key)?;

    let state = env.state();
    let value = state.read_bytes(&key)?;
    match value {
        Some(value) => {
            let len: i64 = value
                .len()
                .try_into()
                .map_err(TxRuntimeError::NumConversionError)?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(value);
            Ok(len)
        }
        None => Ok(HostEnvResult::Fail.to_i64()),
    }
}

/// Read temporary value (not committed to storage) from the given key function
/// exposed to the wasm VM Tx environment. It will try to read from the write
/// log only.
///
/// Returns `-1` when the key is not present, or the length of the data when
/// the key is present (the length may be `0`).
pub fn tx_read_temp<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    key_ptr: u64,
    key_len: u64,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_read {}, key {}", key, key_ptr,);

    let key = Key::parse(key)?;

    let write_log = unsafe { env.ctx.write_log.get() };
    let (log_val, gas) = write_log.read_temp(&key).into_storage_result()?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    match log_val {
        Some(value) => {
            let len: i64 = value
                .len()
                .try_into()
                .map_err(TxRuntimeError::NumConversionError)?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(value.clone());
            Ok(len)
        }
        None => Ok(HostEnvResult::Fail.to_i64()),
    }
}

/// This function is a helper to handle the first step of reading var-len
/// values from the host.
///
/// In cases where we're reading a value from the host in the guest and
/// we don't know the byte size up-front, we have to read it in 2-steps. The
/// first step reads the value into a result buffer and returns the size (if
/// any) back to the guest, the second step reads the value from cache into a
/// pre-allocated buffer with the obtained size.
pub fn tx_result_buffer<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    result_ptr: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
    let value = result_buffer
        .take()
        .ok_or(TxRuntimeError::NoValueInResultBuffer)?;
    let gas = env
        .memory
        .write_bytes(result_ptr, value)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)
}

/// Storage prefix iterator function exposed to the wasm VM Tx environment.
/// It will try to get an iterator from the storage and return the corresponding
/// ID of the iterator, ordered by storage keys.
pub fn tx_iter_prefix<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    prefix_ptr: u64,
    prefix_len: u64,
) -> TxResult<u64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (prefix, gas) = env
        .memory
        .read_string(prefix_ptr, prefix_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_iter_prefix {}", prefix);

    let prefix = Key::parse(prefix)?;

    let write_log = unsafe { env.ctx.write_log.get() };
    let db = unsafe { env.ctx.db.get() };
    let (iter, gas) = namada_state::iter_prefix_post(write_log, db, &prefix)?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    let iterators = unsafe { env.ctx.iterators.get_mut() };
    Ok(iterators
        .insert(iter)
        .ok_or_err_msg("Iterator ID overflow")?
        .id())
}

/// Storage prefix iterator next function exposed to the wasm VM Tx environment.
/// It will try to read from the write log first and if no entry found then from
/// the storage.
///
/// Returns `-1` when the key is not present, or the length of the data when
/// the key is present (the length may be `0`).
pub fn tx_iter_next<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    iter_id: u64,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    tracing::debug!("tx_iter_next iter_id {}", iter_id,);

    let iterators = unsafe { env.ctx.iterators.get_mut() };
    let iter_id = PrefixIteratorId::new(iter_id);
    while let Some((key, val, iter_gas)) = iterators.next(iter_id) {
        let (log_val, log_gas) = {
            let state = env.state();
            let (log_val, log_gas) = state
                .write_log()
                .read(&Key::parse(key.clone())?)
                .into_storage_result()?;
            (log_val.cloned(), log_gas)
        };
        consume_tx_gas::<MEM, D, H, CA>(env, checked!(iter_gas + log_gas)?)?;
        match log_val {
            Some(write_log::StorageModification::Write { value }) => {
                let key_val = borsh::to_vec(&KeyVal { key, val: value })
                    .map_err(TxRuntimeError::EncodingError)?;
                let len: i64 = key_val
                    .len()
                    .try_into()
                    .map_err(TxRuntimeError::NumConversionError)?;
                let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
                result_buffer.replace(key_val);
                return Ok(len);
            }
            Some(write_log::StorageModification::Delete) => {
                // check the next because the key has already deleted
                continue;
            }
            Some(write_log::StorageModification::InitAccount { .. }) => {
                // a VP of a new account doesn't need to be iterated
                continue;
            }
            None => {
                let key_val = borsh::to_vec(&KeyVal { key, val })
                    .map_err(TxRuntimeError::EncodingError)?;
                let len: i64 = key_val
                    .len()
                    .try_into()
                    .map_err(TxRuntimeError::NumConversionError)?;
                let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
                result_buffer.replace(key_val);
                return Ok(len);
            }
        }
    }
    Ok(HostEnvResult::Fail.to_i64())
}

/// Storage write function exposed to the wasm VM Tx environment. The given
/// key/value will be written to the write log.
pub fn tx_write<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    key_ptr: u64,
    key_len: u64,
    val_ptr: u64,
    val_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let (value, gas) = env
        .memory
        .read_bytes(val_ptr, val_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_update {}, {:?}", key, value);

    let key = Key::parse(key)?;
    if key.is_validity_predicate().is_some() {
        tx_validate_vp_code_hash::<MEM, D, H, CA>(env, &value, &None)?;
    }

    check_address_existence::<MEM, D, H, CA>(env, &key)?;

    let mut state = env.state();
    state.write_bytes(&key, value)
}

/// Temporary storage write function exposed to the wasm VM Tx environment. The
/// given key/value will be written only to the write log. It will be never
/// written to the storage.
pub fn tx_write_temp<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    key_ptr: u64,
    key_len: u64,
    val_ptr: u64,
    val_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let (value, gas) = env
        .memory
        .read_bytes(val_ptr, val_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_write_temp {}, {:?}", key, value);

    let key = Key::parse(key)?;

    check_address_existence::<MEM, D, H, CA>(env, &key)?;

    let mut state = env.state();
    let (gas, _size_diff) = state.write_log_mut().write_temp(&key, value)?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)
}

fn check_address_existence<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    key: &Key,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    // Get the token if the key is a balance or minter key
    let token = if let Some([token, _]) = is_any_token_balance_key(key) {
        Some(token)
    } else if let Some(token) = is_any_token_parameter_key(key) {
        Some(token)
    } else {
        is_any_minted_balance_key(key).or_else(|| is_any_minter_key(key))
    };

    let state = env.state();
    for addr in key.find_addresses() {
        // skip if the address is a token address
        if Some(&addr) == token {
            continue;
        }
        // skip the check for implicit and internal addresses
        if let Address::Implicit(_) | Address::Internal(_) = &addr {
            continue;
        }
        let vp_key = Key::validity_predicate(&addr);
        let is_present = state.has_key(&vp_key)?;
        if !is_present {
            tracing::info!(
                "Trying to write into storage with a key containing an \
                 address that doesn't exist: {}",
                addr
            );
            return Err(TxRuntimeError::UnknownAddressStorageModification(
                addr,
            )
            .into());
        }
    }
    Ok(())
}

/// Storage delete function exposed to the wasm VM Tx environment. The given
/// key/value will be written as deleted to the write log.
pub fn tx_delete<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    key_ptr: u64,
    key_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_delete {}", key);

    let key = Key::parse(key)?;
    if key.is_validity_predicate().is_some() {
        return Err(TxRuntimeError::CannotDeleteVp.into());
    }

    let mut state = env.state();
    state.delete(&key)
}

/// Expose the functionality to emit events to the wasm VM's Tx environment.
/// An emitted event will land in the write log.
pub fn tx_emit_event<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    event_ptr: u64,
    event_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (event, gas) = env
        .memory
        .read_bytes(event_ptr, event_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let event: Event = BorshDeserialize::try_from_slice(&event)
        .map_err(TxRuntimeError::EncodingError)?;
    let mut state = env.state();
    let gas = state
        .write_log_mut()
        .emit_event(event)
        .ok_or(TxRuntimeError::GasOverflow)?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)
}

/// Expose the functionality to query events from the wasm VM's Tx environment.
pub fn tx_get_events<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    event_type_ptr: u64,
    event_type_len: u64,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (event_type, gas) = env
        .memory
        .read_string(event_type_ptr, event_type_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let state = env.state();
    let value = {
        let event_type = EventTypeBuilder::new_with_type(event_type).build();

        let events: Vec<_> = state
            .write_log()
            .lookup_events_with_prefix(&event_type)
            .collect();

        events.serialize_to_vec()
    };
    let len: i64 = value
        .len()
        .try_into()
        .map_err(TxRuntimeError::NumConversionError)?;
    let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
    result_buffer.replace(value);
    Ok(len)
}

/// Storage read prior state (before tx execution) function exposed to the wasm
/// VM VP environment. It will try to read from the storage.
///
/// Returns `-1` when the key is not present, or the length of the data when
/// the key is present (the length may be `0`).
pub fn vp_read_pre<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    key_ptr: u64,
    key_len: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    // try to read from the storage
    let key = Key::parse(key)?;
    let state = env.state();
    let value = vp_host_fns::read_pre(gas_meter, &state, &key)?;
    tracing::debug!(
        "vp_read_pre addr {}, key {}, value {:?}",
        unsafe { env.ctx.address.get() },
        key,
        value,
    );
    Ok(match value {
        Some(value) => {
            let len: i64 = value.len().try_into()?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(value);
            len
        }
        None => HostEnvResult::Fail.to_i64(),
    })
}

/// Storage read posterior state (after tx execution) function exposed to the
/// wasm VM VP environment. It will try to read from the write log first and if
/// no entry found then from the storage.
///
/// Returns `-1` when the key is not present, or the length of the data when
/// the key is present (the length may be `0`).
pub fn vp_read_post<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    key_ptr: u64,
    key_len: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    tracing::debug!("vp_read_post {}, key {}", key, key_ptr,);

    // try to read from the write log first
    let key = Key::parse(key)?;
    let state = env.state();
    let value = vp_host_fns::read_post(gas_meter, &state, &key)?;
    Ok(match value {
        Some(value) => {
            let len: i64 = value.len().try_into()?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(value);
            len
        }
        None => HostEnvResult::Fail.to_i64(),
    })
}

/// Storage read temporary state (after tx execution) function exposed to the
/// wasm VM VP environment. It will try to read from only the write log.
///
/// Returns `-1` when the key is not present, or the length of the data when
/// the key is present (the length may be `0`).
pub fn vp_read_temp<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    key_ptr: u64,
    key_len: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    tracing::debug!("vp_read_temp {}, key {}", key, key_ptr);

    // try to read from the write log
    let key = Key::parse(key)?;
    let state = env.state();
    let value = vp_host_fns::read_temp(gas_meter, &state, &key)?;
    Ok(match value {
        Some(value) => {
            let len: i64 = value.len().try_into()?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(value);
            len
        }
        None => HostEnvResult::Fail.to_i64(),
    })
}

/// This function is a helper to handle the first step of reading var-len
/// values from the host.
///
/// In cases where we're reading a value from the host in the guest and
/// we don't know the byte size up-front, we have to read it in 2-steps. The
/// first step reads the value into a result buffer and returns the size (if
/// any) back to the guest, the second step reads the value from cache into a
/// pre-allocated buffer with the obtained size.
pub fn vp_result_buffer<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    result_ptr: u64,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
    let value = result_buffer
        .take()
        .ok_or(Error::new_const("No value found in result buffer"))?;
    let gas = env
        .memory
        .write_bytes(result_ptr, value)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)
}

/// Storage `has_key` in prior state (before tx execution) function exposed to
/// the wasm VM VP environment. It will try to read from the storage.
pub fn vp_has_key_pre<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    key_ptr: u64,
    key_len: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    tracing::debug!("vp_has_key_pre {}, key {}", key, key_ptr,);

    let key = Key::parse(key)?;
    let state = env.state();
    let present = vp_host_fns::has_key_pre(gas_meter, &state, &key)?;
    Ok(HostEnvResult::from(present).to_i64())
}

/// Storage `has_key` in posterior state (after tx execution) function exposed
/// to the wasm VM VP environment. It will try to check the write log first and
/// if no entry found then the storage.
pub fn vp_has_key_post<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    key_ptr: u64,
    key_len: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (key, gas) = env
        .memory
        .read_string(key_ptr, key_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    tracing::debug!("vp_has_key_post {}, key {}", key, key_ptr,);

    let key = Key::parse(key)?;
    let state = env.state();
    let present = vp_host_fns::has_key_post(gas_meter, &state, &key)?;
    Ok(HostEnvResult::from(present).to_i64())
}

/// Storage prefix iterator function for prior state (before tx execution)
/// exposed to the wasm VM VP environment.
///
/// It will try to get an iterator from the storage and return the corresponding
/// ID of the iterator, ordered by storage keys.
pub fn vp_iter_prefix_pre<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    prefix_ptr: u64,
    prefix_len: u64,
) -> Result<u64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (prefix, gas) = env
        .memory
        .read_string(prefix_ptr, prefix_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    tracing::debug!("vp_iter_prefix_pre {}", prefix);

    let prefix = Key::parse(prefix)?;

    let write_log = unsafe { env.ctx.write_log.get() };
    let db = unsafe { env.ctx.db.get() };
    let iter = vp_host_fns::iter_prefix_pre(gas_meter, write_log, db, &prefix)?;

    let iterators = unsafe { env.ctx.iterators.get_mut() };
    Ok(iterators
        .insert(iter)
        .ok_or_err_msg("Iterator ID overflow")?
        .id())
}

/// Storage prefix iterator function for posterior state (after tx execution)
/// exposed to the wasm VM VP environment.
///
/// It will try to get an iterator from the storage and return the corresponding
/// ID of the iterator, ordered by storage keys.
pub fn vp_iter_prefix_post<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    prefix_ptr: u64,
    prefix_len: u64,
) -> Result<u64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (prefix, gas) = env
        .memory
        .read_string(prefix_ptr, prefix_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    tracing::debug!("vp_iter_prefix_post {}", prefix);

    let prefix = Key::parse(prefix)?;

    let write_log = unsafe { env.ctx.write_log.get() };
    let db = unsafe { env.ctx.db.get() };
    let iter =
        vp_host_fns::iter_prefix_post(gas_meter, write_log, db, &prefix)?;

    let iterators = unsafe { env.ctx.iterators.get_mut() };
    Ok(iterators
        .insert(iter)
        .ok_or_err_msg("Iterator ID overflow")?
        .id())
}

/// Storage prefix iterator for prior or posterior state function
/// exposed to the wasm VM VP environment.
///
/// Returns `-1` when the key is not present, or the length of the data when
/// the key is present (the length may be `0`).
pub fn vp_iter_next<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    iter_id: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    tracing::debug!("vp_iter_next iter_id {}", iter_id);

    let iterators = unsafe { env.ctx.iterators.get_mut() };
    let iter_id = PrefixIteratorId::new(iter_id);
    if let Some(iter) = iterators.get_mut(iter_id) {
        let gas_meter = env.ctx.gas_meter();
        if let Some((key, val)) = vp_host_fns::iter_next(gas_meter, iter)? {
            let key_val = KeyVal { key, val }.serialize_to_vec();
            let len: i64 = key_val.len().try_into()?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(key_val);
            return Ok(len);
        }
    }
    Ok(HostEnvResult::Fail.to_i64())
}

/// Verifier insertion function exposed to the wasm VM Tx environment.
pub fn tx_insert_verifier<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    addr_ptr: u64,
    addr_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (addr, gas) = env
        .memory
        .read_string(addr_ptr, addr_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_insert_verifier {}, addr_ptr {}", addr, addr_ptr,);

    let addr = Address::decode(&addr).map_err(TxRuntimeError::AddressError)?;

    let verifiers = unsafe { env.ctx.verifiers.get_mut() };
    // This is not a storage write, use the same multiplier used for a storage
    // read
    consume_tx_gas::<MEM, D, H, CA>(
        env,
        checked!(addr_len * MEMORY_ACCESS_GAS_PER_BYTE)?.into(),
    )?;
    verifiers.insert(addr);

    Ok(())
}

/// Update a validity predicate function exposed to the wasm VM Tx environment
pub fn tx_update_validity_predicate<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    addr_ptr: u64,
    addr_len: u64,
    code_hash_ptr: u64,
    code_hash_len: u64,
    code_tag_ptr: u64,
    code_tag_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (addr, gas) = env
        .memory
        .read_string(addr_ptr, addr_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    let addr = Address::decode(addr).map_err(TxRuntimeError::AddressError)?;
    tracing::debug!("tx_update_validity_predicate for addr {}", addr);

    let (code_tag, gas) = env
        .memory
        .read_bytes(code_tag_ptr, code_tag_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let code_tag = Option::<String>::try_from_slice(&code_tag)
        .map_err(TxRuntimeError::EncodingError)?;

    let key = Key::validity_predicate(&addr);
    let (code_hash, gas) = env
        .memory
        .read_bytes(code_hash_ptr, code_hash_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tx_validate_vp_code_hash::<MEM, D, H, CA>(env, &code_hash, &code_tag)?;

    let mut state = env.state();
    let (gas, _size_diff) = state.write_log_mut().write(&key, code_hash)?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)
}

/// Initialize a new account established address.
#[allow(clippy::too_many_arguments)]
pub fn tx_init_account<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    code_hash_ptr: u64,
    code_hash_len: u64,
    code_tag_ptr: u64,
    code_tag_len: u64,
    entropy_source_ptr: u64,
    entropy_source_len: u64,
    result_ptr: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (code_hash, gas) = env
        .memory
        .read_bytes(code_hash_ptr, code_hash_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    let (code_tag, gas) = env
        .memory
        .read_bytes(code_tag_ptr, code_tag_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let code_tag = Option::<String>::try_from_slice(&code_tag)
        .map_err(TxRuntimeError::EncodingError)?;

    tx_validate_vp_code_hash::<MEM, D, H, CA>(env, &code_hash, &code_tag)?;

    let (entropy_source, gas) = env
        .memory
        .read_bytes(entropy_source_ptr, entropy_source_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;

    tracing::debug!("tx_init_account");

    let code_hash = Hash::try_from(&code_hash[..])
        .map_err(|e| TxRuntimeError::InvalidVpCodeHash(e.to_string()))?;
    let mut state = env.state();
    let (write_log, in_mem, _db) = state.split_borrow();
    let gen = &in_mem.address_gen;
    let (addr, gas) = write_log.init_account(gen, code_hash, &entropy_source);
    let addr_bytes = addr.serialize_to_vec();
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let gas = env
        .memory
        .write_bytes(result_ptr, addr_bytes)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)
}

/// Getting the chain ID function exposed to the wasm VM Tx environment.
pub fn tx_get_chain_id<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    result_ptr: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let state = env.state();
    let (chain_id, gas) = state.in_mem().get_chain_id();
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let gas = env
        .memory
        .write_string(result_ptr, chain_id.to_string())
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)
}

/// Getting the block height function exposed to the wasm VM Tx
/// environment. The height is that of the block to which the current
/// transaction is being applied.
pub fn tx_get_block_height<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
) -> TxResult<u64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let state = env.state();
    let (height, gas) = state.in_mem().get_block_height();
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    Ok(height.0)
}

/// Getting the transaction index function exposed to the wasm VM Tx
/// environment. The index is that of the transaction being applied
/// in the current block.
pub fn tx_get_tx_index<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
) -> TxResult<u32>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    consume_tx_gas::<MEM, D, H, CA>(
        env,
        (TX_INDEX_LENGTH as u64)
            .checked_mul(MEMORY_ACCESS_GAS_PER_BYTE)
            .expect("Consts mul that cannot overflow")
            .into(),
    )?;
    let tx_index = unsafe { env.ctx.tx_index.get() };
    Ok(tx_index.0)
}

/// Getting the block height function exposed to the wasm VM VP
/// environment. The height is that of the block to which the current
/// transaction is being applied.
pub fn vp_get_tx_index<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
) -> Result<u32>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let tx_index = unsafe { env.ctx.tx_index.get() };
    let tx_idx = vp_host_fns::get_tx_index(gas_meter, tx_index)?;
    Ok(tx_idx.0)
}

/// Getting the block epoch function exposed to the wasm VM Tx
/// environment. The epoch is that of the block to which the current
/// transaction is being applied.
pub fn tx_get_block_epoch<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
) -> TxResult<u64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let state = env.state();
    let (epoch, gas) = state.in_mem().get_current_epoch();
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    Ok(epoch.0)
}

/// Get predecessor epochs function exposed to the wasm VM Tx environment.
pub fn tx_get_pred_epochs<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let state = env.state();
    let pred_epochs = state.in_mem().block.pred_epochs.clone();
    let bytes = pred_epochs.serialize_to_vec();
    let len: i64 = bytes
        .len()
        .try_into()
        .map_err(TxRuntimeError::NumConversionError)?;
    let len_u64 = u64::try_from(len)?;
    consume_tx_gas::<MEM, D, H, CA>(
        env,
        checked!(MEMORY_ACCESS_GAS_PER_BYTE * len_u64)?.into(),
    )?;
    let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
    result_buffer.replace(bytes);
    Ok(len)
}

/// Get the native token's address
pub fn tx_get_native_token<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    result_ptr: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    // Gas for getting the native token address from storage
    consume_tx_gas::<MEM, D, H, CA>(
        env,
        (ESTABLISHED_ADDRESS_BYTES_LEN as u64)
            .checked_mul(MEMORY_ACCESS_GAS_PER_BYTE)
            .expect("Consts mul that cannot overflow")
            .into(),
    )?;
    let state = env.state();
    let native_token = state.in_mem().native_token.clone();
    let native_token_string = native_token.encode();
    let gas = env
        .memory
        .write_string(result_ptr, native_token_string)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)
}

/// Getting the block header function exposed to the wasm VM Tx environment.
pub fn tx_get_block_header<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    height: u64,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let state = env.state();
    let (header, gas) =
        StateRead::get_block_header(&state, Some(BlockHeight(height)))?;

    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    Ok(match header {
        Some(h) => {
            let value = h.serialize_to_vec();
            let len: i64 = value
                .len()
                .try_into()
                .map_err(TxRuntimeError::NumConversionError)?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(value);
            len
        }
        None => HostEnvResult::Fail.to_i64(),
    })
}

/// Getting the chain ID function exposed to the wasm VM VP environment.
pub fn vp_get_chain_id<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    result_ptr: u64,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let state = env.state();
    let chain_id = vp_host_fns::get_chain_id(gas_meter, &state)?;
    let gas = env
        .memory
        .write_string(result_ptr, chain_id.to_string())
        .map_err(Into::into)?;
    vp_host_fns::add_gas(gas_meter, gas)
}

/// Getting the block height function exposed to the wasm VM VP
/// environment. The height is that of the block to which the current
/// transaction is being applied.
pub fn vp_get_block_height<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
) -> Result<u64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let state = env.state();
    let height = vp_host_fns::get_block_height(gas_meter, &state)?;
    Ok(height.0)
}

/// Getting the block header function exposed to the wasm VM VP environment.
pub fn vp_get_block_header<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    height: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let state = env.state();
    let (header, gas) =
        StateRead::get_block_header(&state, Some(BlockHeight(height)))?;
    vp_host_fns::add_gas(gas_meter, gas)?;
    Ok(match header {
        Some(h) => {
            let value = h.serialize_to_vec();
            let len: i64 = value.len().try_into()?;
            let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
            result_buffer.replace(value);
            len
        }
        None => HostEnvResult::Fail.to_i64(),
    })
}

/// Getting the transaction hash function exposed to the wasm VM VP environment.
pub fn vp_get_tx_code_hash<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    result_ptr: u64,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let tx = unsafe { env.ctx.tx.get() };
    let cmt = unsafe { env.ctx.cmt.get() };
    let batched_tx = tx.batch_ref_tx(cmt);
    let hash = vp_host_fns::get_tx_code_hash(gas_meter, &batched_tx)?;
    let mut result_bytes = vec![];
    if let Some(hash) = hash {
        result_bytes.push(1);
        result_bytes.extend(hash.0);
    } else {
        result_bytes.push(0);
    };
    let gas = env
        .memory
        .write_bytes(result_ptr, result_bytes)
        .map_err(Into::into)?;
    vp_host_fns::add_gas(gas_meter, gas)
}

/// Getting the block epoch function exposed to the wasm VM VP
/// environment. The epoch is that of the block to which the current
/// transaction is being applied.
pub fn vp_get_block_epoch<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
) -> Result<u64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let state = env.state();
    let epoch = vp_host_fns::get_block_epoch(gas_meter, &state)?;
    Ok(epoch.0)
}

/// Get predecessor epochs function exposed to the wasm VM VP environment.
pub fn vp_get_pred_epochs<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let state = env.state();
    let pred_epochs = vp_host_fns::get_pred_epochs(gas_meter, &state)?;
    let bytes = pred_epochs.serialize_to_vec();
    let len: i64 = bytes.len().try_into()?;
    let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
    result_buffer.replace(bytes);
    Ok(len)
}

/// Expose the functionality to query events from the wasm VM's VP environment.
pub fn vp_get_events<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    event_type_ptr: u64,
    event_type_len: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (event_type, gas) = env
        .memory
        .read_string(event_type_ptr, event_type_len.try_into()?)
        .map_err(Into::into)?;
    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;

    let state = env.state();
    let events = vp_host_fns::get_events(gas_meter, &state, event_type)?;
    let value = events.serialize_to_vec();
    let len: i64 = value.len().try_into()?;
    let result_buffer = unsafe { env.ctx.result_buffer.get_mut() };
    result_buffer.replace(value);
    Ok(len)
}

/// Verify a transaction signature in the host environment for better
/// performance
#[allow(clippy::too_many_arguments)]
pub fn vp_verify_tx_section_signature<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    hash_list_ptr: u64,
    hash_list_len: u64,
    public_keys_map_ptr: u64,
    public_keys_map_len: u64,
    signer_ptr: u64,
    signer_len: u64,
    threshold: u8,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (hash_list, gas) = env
        .memory
        .read_bytes(hash_list_ptr, hash_list_len.try_into()?)
        .map_err(Into::into)?;

    let gas_meter = env.ctx.gas_meter();
    vp_host_fns::add_gas(gas_meter, gas)?;
    let hashes: [Hash; 1] = decode(hash_list)?;

    let (public_keys_map, gas) = env
        .memory
        .read_bytes(public_keys_map_ptr, public_keys_map_len.try_into()?)
        .map_err(Into::into)?;
    vp_host_fns::add_gas(gas_meter, gas)?;
    let public_keys_map: AccountPublicKeysMap = decode(public_keys_map)?;

    let (signer, gas) = env
        .memory
        .read_bytes(signer_ptr, signer_len.try_into()?)
        .map_err(Into::into)?;
    vp_host_fns::add_gas(gas_meter, gas)?;
    let signer: Address = decode(signer)?;

    let tx = unsafe { env.ctx.tx.get() };

    match tx.verify_signatures(
        &HashSet::from_iter(hashes),
        public_keys_map,
        &Some(signer),
        threshold,
        || {
            gas_meter
                .borrow_mut()
                .consume(gas::VERIFY_TX_SIG_GAS.into())
        },
    ) {
        Ok(_) => Ok(()),
        Err(err) => match err {
            namada_tx::VerifySigError::Gas(inner) => {
                Err(vp_host_fns::RuntimeError::OutOfGas(inner))
                    .into_storage_result()
            }
            namada_tx::VerifySigError::InvalidSectionSignature(inner) => {
                Err(vp_host_fns::RuntimeError::InvalidSectionSignature(inner))
                    .into_storage_result()
            }
            err => Err(Error::new_alloc(err.to_string())),
        },
    }
}

/// Log a string from exposed to the wasm VM Tx environment. The message will be
/// printed at the [`tracing::Level::INFO`]. This function is for development
/// only.
pub fn tx_log_string<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    str_ptr: u64,
    str_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (str, _gas) = env
        .memory
        .read_string(str_ptr, str_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    tracing::info!("WASM Transaction log: {}", str);
    Ok(())
}

/// Validate a VP WASM code hash in a tx environment.
fn tx_validate_vp_code_hash<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    code_hash: &[u8],
    code_tag: &Option<String>,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let code_hash = Hash::try_from(code_hash)
        .map_err(|e| TxRuntimeError::InvalidVpCodeHash(e.to_string()))?;

    // First check that code hash corresponds to the code tag if it is present
    if let Some(tag) = code_tag {
        let hash_key = Key::wasm_hash(tag);
        let (result, gas) = env.state().db_read(&hash_key)?;

        consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
        if let Some(tag_hash) = result {
            let tag_hash = Hash::try_from(&tag_hash[..]).map_err(|e| {
                TxRuntimeError::InvalidVpCodeHash(e.to_string())
            })?;
            if tag_hash != code_hash {
                return Err(TxRuntimeError::InvalidVpCodeHash(
                    "The VP code tag does not correspond to the given code \
                     hash"
                        .to_string(),
                )
                .into());
            }
        } else {
            return Err(TxRuntimeError::InvalidVpCodeHash(
                "The VP code tag doesn't exist".to_string(),
            )
            .into());
        }
    }

    // Then check that VP code hash is in the allowlist.
    if !namada_parameters::is_vp_allowed(&env.ctx.state(), &code_hash)? {
        return Err(TxRuntimeError::DisallowedVp.into());
    }

    // Then check that the corresponding VP code does indeed exist
    let code_key = Key::wasm_code(&code_hash);
    let is_present = env.state().has_key(&code_key)?;
    if !is_present {
        return Err(TxRuntimeError::InvalidVpCodeHash(
            "The corresponding VP code doesn't exist".to_string(),
        )
        .into());
    }
    Ok(())
}

/// Set the sentinel for an invalid tx section commitment
pub fn tx_set_commitment_sentinel<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
) where
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    MEM: VmMemory,
    CA: WasmCacheAccess,
{
    let sentinel = unsafe { env.ctx.sentinel.get() };
    sentinel.borrow_mut().set_invalid_commitment();
}

/// Verify a transaction signature
#[allow(clippy::too_many_arguments)]
pub fn tx_verify_tx_section_signature<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    hash_list_ptr: u64,
    hash_list_len: u64,
    public_keys_map_ptr: u64,
    public_keys_map_len: u64,
    threshold: u8,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (hash_list, gas) = env
        .memory
        .read_bytes(hash_list_ptr, hash_list_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;

    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let hashes = <[Hash; 1]>::try_from_slice(&hash_list)
        .map_err(TxRuntimeError::EncodingError)?;

    let (public_keys_map, gas) = env
        .memory
        .read_bytes(public_keys_map_ptr, public_keys_map_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let public_keys_map =
        AccountPublicKeysMap::try_from_slice(&public_keys_map)
            .map_err(TxRuntimeError::EncodingError)?;

    let tx = unsafe { env.ctx.tx.get() };

    let (gas_meter, sentinel) = env.ctx.gas_meter_and_sentinel();
    match tx.verify_signatures(
        &HashSet::from_iter(hashes),
        public_keys_map,
        &None,
        threshold,
        || {
            gas_meter
                .borrow_mut()
                .consume(gas::VERIFY_TX_SIG_GAS.into())
        },
    ) {
        Ok(_) => Ok(HostEnvResult::Success.to_i64()),
        Err(err) => match err {
            namada_tx::VerifySigError::Gas(inner) => {
                sentinel.borrow_mut().set_out_of_gas();
                Err(TxRuntimeError::OutOfGas(inner))
            }
            namada_tx::VerifySigError::InvalidSectionSignature(_) => {
                Ok(HostEnvResult::Fail.to_i64())
            }
            _ => Ok(HostEnvResult::Fail.to_i64()),
        },
    }
    .into_storage_result()
}

/// Appends the new note commitments to the tree in storage
pub fn tx_update_masp_note_commitment_tree<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    transaction_ptr: u64,
    transaction_len: u64,
) -> TxResult<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (serialized_transaction, gas) = env
        .memory
        .read_bytes(transaction_ptr, transaction_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;

    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let transaction = MaspTransaction::try_from_slice(&serialized_transaction)
        .map_err(TxRuntimeError::EncodingError)?;

    match namada_token::utils::update_note_commitment_tree(
        &mut env.state(),
        &transaction,
    ) {
        Ok(()) => Ok(HostEnvResult::Success.to_i64()),
        Err(_) => {
            // NOTE: sentinel for gas errors is already set by the
            // update_note_commitment_tree function which in turn calls other
            // host functions
            Ok(HostEnvResult::Fail.to_i64())
        }
    }
}

/// Yield a byte array value from the guest.
pub fn tx_yield_value<MEM, D, H, CA>(
    env: &mut TxVmEnv<MEM, D, H, CA>,
    buf_ptr: u64,
    buf_len: u64,
) -> TxResult<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    CA: WasmCacheAccess,
{
    let (value_to_yield, gas) = env
        .memory
        .read_bytes(buf_ptr, buf_len.try_into()?)
        .map_err(|e| TxRuntimeError::MemoryError(Box::new(e)))?;
    consume_tx_gas::<MEM, D, H, CA>(env, gas)?;
    let host_buf = unsafe { env.ctx.yielded_value.get_mut() };
    host_buf.replace(value_to_yield);
    Ok(())
}

/// Evaluate a validity predicate with the given input data.
pub fn vp_eval<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    vp_code_hash_ptr: u64,
    vp_code_hash_len: u64,
    input_data_ptr: u64,
    input_data_len: u64,
) -> Result<i64>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator<Db = D, H = H, Eval = EVAL, CA = CA>,
    CA: WasmCacheAccess,
{
    let (vp_code_hash, gas) = env
        .memory
        .read_bytes(vp_code_hash_ptr, vp_code_hash_len.try_into()?)
        .map_err(Into::into)?;

    // The borrowed `gas_meter` must be dropped before eval,
    // which has to borrow it too.
    let tx = {
        let gas_meter = env.ctx.gas_meter();
        vp_host_fns::add_gas(gas_meter, gas)?;

        let (input_data, gas) = env
            .memory
            .read_bytes(input_data_ptr, input_data_len.try_into()?)
            .map_err(Into::into)?;
        vp_host_fns::add_gas(gas_meter, gas)?;
        let tx: BatchedTx = decode(input_data)?;
        tx
    };

    let eval_runner = unsafe { env.ctx.eval_runner.get() };
    let vp_code_hash = Hash(vp_code_hash.try_into().map_err(|e| {
        Error::new(std::io::Error::new(
            std::io::ErrorKind::InvalidData,
            format!("Not a valid hash: {:?}", e),
        ))
    })?);
    let batch_ref = BatchedTxRef {
        tx: &tx.tx,
        cmt: &tx.cmt,
    };
    Ok(eval_runner
        .eval(env.ctx.clone(), vp_code_hash, batch_ref)
        .to_i64())
}

/// Get the native token's address
pub fn vp_get_native_token<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    result_ptr: u64,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let gas_meter = env.ctx.gas_meter();
    let state = env.state();
    let native_token = vp_host_fns::get_native_token(gas_meter, &state)?;
    let native_token_string = native_token.encode();
    let gas = env
        .memory
        .write_string(result_ptr, native_token_string)
        .map_err(Into::into)?;
    vp_host_fns::add_gas(gas_meter, gas)
}

/// Log a string from exposed to the wasm VM VP environment. The message will be
/// printed at the [`tracing::Level::INFO`]. This function is for development
/// only.
pub fn vp_log_string<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    str_ptr: u64,
    str_len: u64,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (str, _gas) = env
        .memory
        .read_string(str_ptr, str_len.try_into()?)
        .map_err(Into::into)?;
    tracing::info!("WASM Validity predicate log: {}", str);
    Ok(())
}

/// Yield a byte array value from the guest.
pub fn vp_yield_value<MEM, D, H, EVAL, CA>(
    env: &mut VpVmEnv<MEM, D, H, EVAL, CA>,
    buf_ptr: u64,
    buf_len: u64,
) -> Result<()>
where
    MEM: VmMemory,
    D: 'static + DB + for<'iter> DBIter<'iter>,
    H: 'static + StorageHasher,
    EVAL: VpEvaluator,
    CA: WasmCacheAccess,
{
    let (value_to_yield, gas) = env
        .memory
        .read_bytes(buf_ptr, buf_len.try_into()?)
        .map_err(Into::into)?;
    vp_host_fns::add_gas(env.ctx.gas_meter(), gas)?;
    let host_buf = unsafe { env.ctx.yielded_value.get_mut() };
    host_buf.replace(value_to_yield);
    Ok(())
}

/// A helper module for testing
#[cfg(feature = "testing")]
pub mod testing {
    use std::rc::Rc;

    use super::*;
    use crate::memory::testing::NativeMemory;
    use crate::wasm::memory::WasmMemory;

    /// Setup a transaction environment
    #[allow(clippy::too_many_arguments)]
    pub fn tx_env<S, CA>(
        state: &mut S,
        iterators: &mut PrefixIterators<'static, <S as StateRead>::D>,
        verifiers: &mut BTreeSet<Address>,
        gas_meter: &RefCell<TxGasMeter>,
        sentinel: &RefCell<TxSentinel>,
        tx: &Tx,
        cmt: &TxCommitments,
        tx_index: &TxIndex,
        result_buffer: &mut Option<Vec<u8>>,
        yielded_value: &mut Option<Vec<u8>>,
        #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache<CA>,
        #[cfg(feature = "wasm-runtime")] tx_wasm_cache: &mut TxCache<CA>,
    ) -> TxVmEnv<NativeMemory, <S as StateRead>::D, <S as StateRead>::H, CA>
    where
        S: State,
        CA: WasmCacheAccess,
    {
        let (write_log, in_mem, db) = state.split_borrow();
        TxVmEnv::new(
            NativeMemory,
            write_log,
            in_mem,
            db,
            iterators,
            gas_meter,
            sentinel,
            tx,
            cmt,
            tx_index,
            verifiers,
            result_buffer,
            yielded_value,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache,
            #[cfg(feature = "wasm-runtime")]
            tx_wasm_cache,
        )
    }

    /// Setup a transaction environment
    #[allow(clippy::too_many_arguments)]
    pub fn tx_env_with_wasm_memory<S, CA>(
        state: &mut S,
        iterators: &mut PrefixIterators<'static, <S as StateRead>::D>,
        verifiers: &mut BTreeSet<Address>,
        gas_meter: &RefCell<TxGasMeter>,
        sentinel: &RefCell<TxSentinel>,
        tx: &Tx,
        cmt: &TxCommitments,
        tx_index: &TxIndex,
        result_buffer: &mut Option<Vec<u8>>,
        yielded_value: &mut Option<Vec<u8>>,
        store: Rc<RefCell<wasmer::Store>>,
        #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache<CA>,
        #[cfg(feature = "wasm-runtime")] tx_wasm_cache: &mut TxCache<CA>,
    ) -> TxVmEnv<WasmMemory, <S as StateRead>::D, <S as StateRead>::H, CA>
    where
        S: State,
        CA: WasmCacheAccess,
    {
        let wasm_memory = {
            let mut borrowed_store = store.borrow_mut();
            crate::wasm::memory::prepare_tx_memory(&mut *borrowed_store)
                .unwrap()
        };

        let (write_log, in_mem, db) = state.split_borrow();
        let mut env = TxVmEnv::new(
            WasmMemory::new(Rc::downgrade(&store)),
            write_log,
            in_mem,
            db,
            iterators,
            gas_meter,
            sentinel,
            tx,
            cmt,
            tx_index,
            verifiers,
            result_buffer,
            yielded_value,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache,
            #[cfg(feature = "wasm-runtime")]
            tx_wasm_cache,
        );

        env.memory.init_from(&wasm_memory);
        env
    }

    /// Setup a validity predicate environment
    #[allow(clippy::too_many_arguments)]
    pub fn vp_env<S, EVAL, CA>(
        address: &Address,
        state: &S,
        iterators: &mut PrefixIterators<'static, <S as StateRead>::D>,
        gas_meter: &RefCell<VpGasMeter>,
        tx: &Tx,
        cmt: &TxCommitments,
        tx_index: &TxIndex,
        verifiers: &BTreeSet<Address>,
        result_buffer: &mut Option<Vec<u8>>,
        yielded_value: &mut Option<Vec<u8>>,
        keys_changed: &BTreeSet<Key>,
        eval_runner: &EVAL,
        #[cfg(feature = "wasm-runtime")] vp_wasm_cache: &mut VpCache<CA>,
    ) -> VpVmEnv<NativeMemory, <S as StateRead>::D, <S as StateRead>::H, EVAL, CA>
    where
        S: StateRead,
        EVAL: VpEvaluator,
        CA: WasmCacheAccess,
    {
        VpVmEnv::new(
            NativeMemory,
            address,
            state.write_log(),
            state.in_mem(),
            state.db(),
            gas_meter,
            tx,
            cmt,
            tx_index,
            iterators,
            verifiers,
            result_buffer,
            yielded_value,
            keys_changed,
            eval_runner,
            #[cfg(feature = "wasm-runtime")]
            vp_wasm_cache,
        )
    }
}