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
use std::{
    collections::BTreeMap,
    convert::{TryFrom, TryInto},
    ffi::OsStr,
    fs,
    ops::Deref,
    path::{Path, PathBuf},
    rc::Rc,
    sync::Arc,
};

use filesize::PathExt;
use lmdb::DatabaseFlags;
use log::LevelFilter;
use num_rational::Ratio;
use num_traits::CheckedMul;

use casper_execution_engine::{
    core::{
        engine_state::{
            self,
            engine_config::RefundHandling,
            era_validators::GetEraValidatorsRequest,
            execute_request::ExecuteRequest,
            execution_result::ExecutionResult,
            run_genesis_request::RunGenesisRequest,
            step::{EvictItem, StepRequest, StepSuccess},
            BalanceResult, EngineConfig, EngineConfigBuilder, EngineState, Error, GenesisSuccess,
            GetBidsRequest, PruneConfig, PruneResult, QueryRequest, QueryResult, RewardItem,
            StepError, SystemContractRegistry, UpgradeConfig, UpgradeSuccess,
            DEFAULT_MAX_QUERY_DEPTH,
        },
        execution,
    },
    shared::{
        additive_map::AdditiveMap,
        execution_journal::ExecutionJournal,
        logging::{self, Settings, Style},
        newtypes::CorrelationId,
        system_config::{
            auction_costs::AuctionCosts, handle_payment_costs::HandlePaymentCosts,
            mint_costs::MintCosts,
        },
        transform::Transform,
        utils::OS_PAGE_SIZE,
    },
    storage::{
        global_state::{
            in_memory::InMemoryGlobalState, lmdb::LmdbGlobalState, scratch::ScratchGlobalState,
            CommitProvider, StateProvider, StateReader,
        },
        transaction_source::lmdb::LmdbEnvironment,
        trie::{merkle_proof::TrieMerkleProof, Trie},
        trie_store::lmdb::LmdbTrieStore,
    },
};
use casper_hashing::Digest;
use casper_types::{
    account::{Account, AccountHash},
    bytesrepr::{self, FromBytes},
    runtime_args,
    system::{
        auction::{
            Bids, EraValidators, UnbondingPurse, UnbondingPurses, ValidatorWeights, WithdrawPurses,
            ARG_ERA_END_TIMESTAMP_MILLIS, ARG_EVICTED_VALIDATORS, AUCTION_DELAY_KEY, ERA_ID_KEY,
            METHOD_RUN_AUCTION, UNBONDING_DELAY_KEY,
        },
        mint::{ROUND_SEIGNIORAGE_RATE_KEY, TOTAL_SUPPLY_KEY},
        AUCTION, HANDLE_PAYMENT, MINT, STANDARD_PAYMENT,
    },
    CLTyped, CLValue, Contract, ContractHash, ContractPackage, ContractPackageHash, ContractWasm,
    DeployHash, DeployInfo, EraId, Gas, Key, KeyTag, Motes, ProtocolVersion, PublicKey,
    RuntimeArgs, StoredValue, Transfer, TransferAddr, URef, U512,
};

use crate::{
    chainspec_config::{ChainspecConfig, CoreConfig, PRODUCTION_CHAINSPEC_PATH},
    utils, ExecuteRequestBuilder, StepRequestBuilder, DEFAULT_GAS_PRICE, DEFAULT_PROPOSER_ADDR,
    DEFAULT_PROTOCOL_VERSION, SYSTEM_ADDR,
};

/// LMDB initial map size is calculated based on DEFAULT_LMDB_PAGES and systems page size.
const DEFAULT_LMDB_PAGES: usize = 256_000_000;

/// LMDB max readers
///
/// The default value is chosen to be the same as the node itself.
const DEFAULT_MAX_READERS: u32 = 512;

/// This is appended to the data dir path provided to the `LmdbWasmTestBuilder`".
const GLOBAL_STATE_DIR: &str = "global_state";

/// Wasm test builder where state is held entirely in memory.
pub type InMemoryWasmTestBuilder = WasmTestBuilder<InMemoryGlobalState>;
/// Wasm test builder where state is held in LMDB.
pub type LmdbWasmTestBuilder = WasmTestBuilder<LmdbGlobalState>;

/// Builder for simple WASM test
pub struct WasmTestBuilder<S> {
    /// [`EngineState`] is wrapped in [`Rc`] to work around a missing [`Clone`] implementation
    engine_state: Rc<EngineState<S>>,
    /// [`ExecutionResult`] is wrapped in [`Rc`] to work around a missing [`Clone`] implementation
    exec_results: Vec<Vec<Rc<ExecutionResult>>>,
    upgrade_results: Vec<Result<UpgradeSuccess, engine_state::Error>>,
    prune_results: Vec<Result<PruneResult, engine_state::Error>>,
    genesis_hash: Option<Digest>,
    /// Post state hash.
    post_state_hash: Option<Digest>,
    /// Cached transform maps after subsequent successful runs i.e. `transforms[0]` is for first
    /// exec call etc.
    transforms: Vec<ExecutionJournal>,
    /// Cached system account.
    system_account: Option<Account>,
    /// Genesis transforms
    genesis_transforms: Option<AdditiveMap<Key, Transform>>,
    /// Scratch global state used for in-memory execution and commit optimization.
    scratch_engine_state: Option<EngineState<ScratchGlobalState>>,
    /// System contract registry
    system_contract_registry: Option<SystemContractRegistry>,
    /// Global state dir, for implementations that define one.
    global_state_dir: Option<PathBuf>,
}

impl<S> WasmTestBuilder<S> {
    fn initialize_logging() {
        let log_settings = Settings::new(LevelFilter::Error).with_style(Style::HumanReadable);
        let _ = logging::initialize(log_settings);
    }
}

impl Default for InMemoryWasmTestBuilder {
    fn default() -> Self {
        Self::new_with_chainspec(&*PRODUCTION_CHAINSPEC_PATH, None)
    }
}

// TODO: Deriving `Clone` for `WasmTestBuilder<S>` doesn't work correctly (unsure why), so
// implemented by hand here.  Try to derive in the future with a different compiler version.
impl<S> Clone for WasmTestBuilder<S> {
    fn clone(&self) -> Self {
        WasmTestBuilder {
            engine_state: Rc::clone(&self.engine_state),
            exec_results: self.exec_results.clone(),
            upgrade_results: self.upgrade_results.clone(),
            prune_results: self.prune_results.clone(),
            genesis_hash: self.genesis_hash,
            post_state_hash: self.post_state_hash,
            transforms: self.transforms.clone(),
            system_account: None,
            genesis_transforms: self.genesis_transforms.clone(),
            scratch_engine_state: None,
            system_contract_registry: self.system_contract_registry.clone(),
            global_state_dir: self.global_state_dir.clone(),
        }
    }
}

impl InMemoryWasmTestBuilder {
    /// Returns an [`InMemoryWasmTestBuilder`] initialized with an engine config instance.
    pub fn new_with_config(engine_config: EngineConfig) -> Self {
        Self::initialize_logging();

        let global_state = InMemoryGlobalState::empty().expect("should create global state");

        let genesis_hash = global_state.empty_root();

        let engine_state = EngineState::new(global_state, engine_config);

        WasmTestBuilder {
            exec_results: Vec::new(),
            upgrade_results: Vec::new(),
            prune_results: Vec::new(),
            engine_state: Rc::new(engine_state),
            genesis_hash: Some(genesis_hash),
            post_state_hash: Some(genesis_hash),
            transforms: Vec::new(),
            system_account: None,
            genesis_transforms: None,
            scratch_engine_state: None,
            system_contract_registry: None,
            global_state_dir: None,
        }
    }

    /// Returns an [`InMemoryWasmTestBuilder`].
    pub fn new(
        global_state: InMemoryGlobalState,
        engine_config: EngineConfig,
        maybe_post_state_hash: Option<Digest>,
    ) -> Self {
        Self::initialize_logging();
        let engine_state = EngineState::new(global_state, engine_config);
        WasmTestBuilder {
            engine_state: Rc::new(engine_state),
            exec_results: Vec::new(),
            upgrade_results: Vec::new(),
            prune_results: Vec::new(),
            genesis_hash: maybe_post_state_hash,
            post_state_hash: maybe_post_state_hash,
            transforms: Vec::new(),
            system_account: None,
            genesis_transforms: None,
            scratch_engine_state: None,
            system_contract_registry: None,
            global_state_dir: None,
        }
    }

    /// Returns an [`InMemoryWasmTestBuilder`] instantiated using values from a given chainspec.
    pub fn new_with_chainspec<P: AsRef<Path>>(
        chainspec_path: P,
        post_state_hash: Option<Digest>,
    ) -> Self {
        let chainspec_config = ChainspecConfig::from_chainspec_path(chainspec_path)
            .expect("must build chainspec configuration");

        // if you get a compilation error here, make sure to update the builder below accordingly
        let ChainspecConfig {
            core_config,
            wasm_config,
            system_costs_config,
        } = chainspec_config;
        let CoreConfig {
            validator_slots: _,
            auction_delay: _,
            locked_funds_period: _,
            vesting_schedule_period,
            unbonding_delay: _,
            round_seigniorage_rate: _,
            max_associated_keys,
            max_runtime_call_stack_height,
            minimum_delegation_amount,
            strict_argument_checking,
            max_delegators_per_validator,
            refund_handling,
            fee_handling,
        } = core_config;

        let engine_config = EngineConfigBuilder::new()
            .with_max_query_depth(DEFAULT_MAX_QUERY_DEPTH)
            .with_max_associated_keys(max_associated_keys)
            .with_max_runtime_call_stack_height(max_runtime_call_stack_height)
            .with_minimum_delegation_amount(minimum_delegation_amount)
            .with_strict_argument_checking(strict_argument_checking)
            .with_vesting_schedule_period_millis(vesting_schedule_period.millis())
            .with_max_delegators_per_validator(max_delegators_per_validator)
            .with_wasm_config(wasm_config)
            .with_system_config(system_costs_config)
            .with_refund_handling(refund_handling)
            .with_fee_handling(fee_handling)
            .build();

        let global_state = InMemoryGlobalState::empty().expect("should create global state");

        Self::new(global_state, engine_config, post_state_hash)
    }
}

impl LmdbWasmTestBuilder {
    /// Upgrades the execution engine using the scratch trie.
    pub fn upgrade_with_upgrade_request_using_scratch(
        &mut self,
        engine_config: EngineConfig,
        upgrade_config: &mut UpgradeConfig,
    ) -> &mut Self {
        let pre_state_hash = self.post_state_hash.expect("should have state hash");
        upgrade_config.with_pre_state_hash(pre_state_hash);

        let engine_state = Rc::get_mut(&mut self.engine_state).unwrap();
        engine_state.update_config(engine_config);

        let scratch_state = self.engine_state.get_scratch_engine_state();
        let pre_state_hash = upgrade_config.pre_state_hash();
        let mut result = scratch_state
            .commit_upgrade(CorrelationId::new(), upgrade_config.clone())
            .unwrap();
        result.post_state_hash = self
            .engine_state
            .write_scratch_to_db(pre_state_hash, scratch_state.into_inner())
            .unwrap();
        self.engine_state.flush_environment().unwrap();

        let result = Ok(result);

        if let Ok(UpgradeSuccess {
            post_state_hash,
            execution_effect: _,
        }) = result
        {
            self.post_state_hash = Some(post_state_hash);

            if let Ok(StoredValue::CLValue(cl_registry)) =
                self.query(self.post_state_hash, Key::SystemContractRegistry, &[])
            {
                let registry = CLValue::into_t::<SystemContractRegistry>(cl_registry).unwrap();
                self.system_contract_registry = Some(registry);
            }
        }

        self.upgrade_results.push(result);
        self
    }

    /// Returns an [`LmdbWasmTestBuilder`] with configuration.
    pub fn new_with_config<T: AsRef<OsStr> + ?Sized>(
        data_dir: &T,
        engine_config: EngineConfig,
    ) -> Self {
        Self::initialize_logging();
        let page_size = *OS_PAGE_SIZE;
        let global_state_dir = Self::global_state_dir(data_dir);
        Self::create_global_state_dir(&global_state_dir);
        let environment = Arc::new(
            LmdbEnvironment::new(
                &global_state_dir,
                page_size * DEFAULT_LMDB_PAGES,
                DEFAULT_MAX_READERS,
                true,
            )
            .expect("should create LmdbEnvironment"),
        );
        let trie_store = Arc::new(
            LmdbTrieStore::new(&environment, None, DatabaseFlags::empty())
                .expect("should create LmdbTrieStore"),
        );

        let global_state =
            LmdbGlobalState::empty(environment, trie_store).expect("should create LmdbGlobalState");

        let engine_state = EngineState::new(global_state, engine_config);
        WasmTestBuilder {
            engine_state: Rc::new(engine_state),
            exec_results: Vec::new(),
            upgrade_results: Vec::new(),
            prune_results: Vec::new(),
            genesis_hash: None,
            post_state_hash: None,
            transforms: Vec::new(),
            system_account: None,
            genesis_transforms: None,
            scratch_engine_state: None,
            system_contract_registry: None,
            global_state_dir: Some(global_state_dir),
        }
    }

    /// Returns an [`LmdbWasmTestBuilder`] with configuration and values from
    /// a given chainspec.
    pub fn new_with_chainspec<T: AsRef<OsStr> + ?Sized, P: AsRef<Path>>(
        data_dir: &T,
        chainspec_path: P,
    ) -> Self {
        let chainspec_config = ChainspecConfig::from_chainspec_path(chainspec_path)
            .expect("must build chainspec configuration");
        Self::new_with_config(data_dir, EngineConfig::from(chainspec_config))
    }

    /// Returns an [`LmdbWasmTestBuilder`] with configuration and values from
    /// the production chainspec.
    pub fn new_with_production_chainspec<T: AsRef<OsStr> + ?Sized>(data_dir: &T) -> Self {
        Self::new_with_chainspec(data_dir, &*PRODUCTION_CHAINSPEC_PATH)
    }

    /// Flushes the LMDB environment to disk.
    pub fn flush_environment(&self) {
        let engine_state = &*self.engine_state;
        engine_state.flush_environment().unwrap();
    }

    /// Returns a new [`LmdbWasmTestBuilder`].
    pub fn new<T: AsRef<OsStr> + ?Sized>(data_dir: &T) -> Self {
        Self::new_with_config(data_dir, Default::default())
    }

    /// Creates a new instance of builder using the supplied configurations, opening wrapped LMDBs
    /// (e.g. in the Trie and Data stores) rather than creating them.
    pub fn open<T: AsRef<OsStr> + ?Sized>(
        data_dir: &T,
        engine_config: EngineConfig,
        post_state_hash: Digest,
    ) -> Self {
        let global_state_path = Self::global_state_dir(data_dir);
        Self::open_raw(global_state_path, engine_config, post_state_hash)
    }

    /// Creates a new instance of builder using the supplied configurations, opening wrapped LMDBs
    /// (e.g. in the Trie and Data stores) rather than creating them.
    /// Differs from `open` in that it doesn't append `GLOBAL_STATE_DIR` to the supplied path.
    pub fn open_raw<T: AsRef<Path>>(
        global_state_dir: T,
        engine_config: EngineConfig,
        post_state_hash: Digest,
    ) -> Self {
        Self::initialize_logging();
        let page_size = *OS_PAGE_SIZE;
        Self::create_global_state_dir(&global_state_dir);
        let environment = Arc::new(
            LmdbEnvironment::new(
                &global_state_dir,
                page_size * DEFAULT_LMDB_PAGES,
                DEFAULT_MAX_READERS,
                true,
            )
            .expect("should create LmdbEnvironment"),
        );
        let trie_store =
            Arc::new(LmdbTrieStore::open(&environment, None).expect("should open LmdbTrieStore"));

        let global_state =
            LmdbGlobalState::empty(environment, trie_store).expect("should create LmdbGlobalState");

        let engine_state = EngineState::new(global_state, engine_config);

        let mut builder = WasmTestBuilder {
            engine_state: Rc::new(engine_state),
            exec_results: Vec::new(),
            upgrade_results: Vec::new(),
            prune_results: Vec::new(),
            genesis_hash: None,
            post_state_hash: Some(post_state_hash),
            transforms: Vec::new(),
            system_account: None,
            genesis_transforms: None,
            scratch_engine_state: None,
            system_contract_registry: None,
            global_state_dir: None,
        };

        builder.system_contract_registry =
            builder.query_system_contract_registry(Some(post_state_hash));

        builder
    }

    fn create_global_state_dir<T: AsRef<Path>>(global_state_path: T) {
        fs::create_dir_all(&global_state_path).unwrap_or_else(|_| {
            panic!(
                "Expected to create {}",
                global_state_path.as_ref().display()
            )
        });
    }

    fn global_state_dir<T: AsRef<OsStr> + ?Sized>(data_dir: &T) -> PathBuf {
        let mut path = PathBuf::from(data_dir);
        path.push(GLOBAL_STATE_DIR);
        path
    }

    /// Returns the file size on disk of the backing lmdb file behind LmdbGlobalState.
    pub fn lmdb_on_disk_size(&self) -> Option<u64> {
        if let Some(path) = self.global_state_dir.as_ref() {
            let mut path = path.clone();
            path.push("data.lmdb");
            return path.as_path().size_on_disk().ok();
        }
        None
    }

    /// Execute and commit transforms from an ExecuteRequest into a scratch global state.
    /// You MUST call write_scratch_to_lmdb to flush these changes to LmdbGlobalState.
    pub fn scratch_exec_and_commit(&mut self, mut exec_request: ExecuteRequest) -> &mut Self {
        if self.scratch_engine_state.is_none() {
            self.scratch_engine_state = Some(self.engine_state.get_scratch_engine_state());
        }

        let cached_state = self
            .scratch_engine_state
            .as_ref()
            .expect("scratch state should exist");

        // Scratch still requires that one deploy be executed and committed at a time.
        let exec_request = {
            let hash = self.post_state_hash.expect("expected post_state_hash");
            exec_request.parent_state_hash = hash;
            exec_request
        };

        let mut exec_results = Vec::new();
        // First execute the request against our scratch global state.
        let maybe_exec_results = cached_state.run_execute(CorrelationId::new(), exec_request);
        for execution_result in maybe_exec_results.unwrap() {
            let journal = execution_result.execution_journal().clone();
            let transforms: AdditiveMap<Key, Transform> = journal.clone().into();
            let _post_state_hash = cached_state
                .apply_effect(
                    CorrelationId::new(),
                    self.post_state_hash.expect("requires a post_state_hash"),
                    transforms,
                )
                .expect("should commit");

            // Save transforms and execution results for WasmTestBuilder.
            self.transforms.push(journal);
            exec_results.push(Rc::new(execution_result))
        }
        self.exec_results.push(exec_results);
        self
    }

    /// Commit scratch to global state, and reset the scratch cache.
    pub fn write_scratch_to_db(&mut self) -> &mut Self {
        let prestate_hash = self.post_state_hash.expect("Should have genesis hash");
        if let Some(scratch) = self.scratch_engine_state.take() {
            let new_state_root = self
                .engine_state
                .write_scratch_to_db(prestate_hash, scratch.into_inner())
                .unwrap();
            self.post_state_hash = Some(new_state_root);
        }
        self
    }

    /// run step against scratch global state.
    pub fn step_with_scratch(&mut self, step_request: StepRequest) -> &mut Self {
        if self.scratch_engine_state.is_none() {
            self.scratch_engine_state = Some(self.engine_state.get_scratch_engine_state());
        }

        let cached_state = self
            .scratch_engine_state
            .as_ref()
            .expect("scratch state should exist");

        cached_state
            .commit_step(CorrelationId::new(), step_request)
            .expect("unable to run step request against scratch global state");
        self
    }
}

impl<S> WasmTestBuilder<S>
where
    S: StateProvider + CommitProvider,
    engine_state::Error: From<S::Error>,
    S::Error: Into<execution::Error>,
{
    /// Takes a [`RunGenesisRequest`], executes the request and returns Self.
    pub fn run_genesis(&mut self, run_genesis_request: &RunGenesisRequest) -> &mut Self {
        let GenesisSuccess {
            post_state_hash,
            execution_effect,
        } = self
            .engine_state
            .commit_genesis(
                CorrelationId::new(),
                run_genesis_request.genesis_config_hash(),
                run_genesis_request.protocol_version(),
                run_genesis_request.ee_config(),
                run_genesis_request.chainspec_registry().clone(),
            )
            .expect("Unable to get genesis response");

        let transforms = execution_effect.transforms;

        self.system_contract_registry = self.query_system_contract_registry(Some(post_state_hash));

        self.genesis_hash = Some(post_state_hash);
        self.post_state_hash = Some(post_state_hash);
        self.genesis_transforms = Some(transforms);
        self.system_account = self.get_account(*SYSTEM_ADDR);
        self
    }

    fn query_system_contract_registry(
        &mut self,
        post_state_hash: Option<Digest>,
    ) -> Option<SystemContractRegistry> {
        match self.query(post_state_hash, Key::SystemContractRegistry, &[]) {
            Ok(StoredValue::CLValue(cl_registry)) => {
                let system_contract_registry =
                    CLValue::into_t::<SystemContractRegistry>(cl_registry).unwrap();
                Some(system_contract_registry)
            }
            Ok(_) => None,
            Err(_) => None,
        }
    }

    /// Queries state for a [`StoredValue`].
    pub fn query(
        &self,
        maybe_post_state: Option<Digest>,
        base_key: Key,
        path: &[String],
    ) -> Result<StoredValue, String> {
        let post_state = maybe_post_state
            .or(self.post_state_hash)
            .expect("builder must have a post-state hash");

        let query_request = QueryRequest::new(post_state, base_key, path.to_vec());

        let query_result = self
            .engine_state
            .run_query(CorrelationId::new(), query_request)
            .expect("should get query response");

        if let QueryResult::Success { value, .. } = query_result {
            return Ok(value.deref().clone());
        }

        Err(format!("{:?}", query_result))
    }

    /// Queries state for a dictionary item.
    pub fn query_dictionary_item(
        &self,
        maybe_post_state: Option<Digest>,
        dictionary_seed_uref: URef,
        dictionary_item_key: &str,
    ) -> Result<StoredValue, String> {
        let dictionary_address =
            Key::dictionary(dictionary_seed_uref, dictionary_item_key.as_bytes());
        let empty_path: Vec<String> = vec![];
        self.query(maybe_post_state, dictionary_address, &empty_path)
    }

    /// Queries for a [`StoredValue`] and returns the [`StoredValue`] and a Merkle proof.
    pub fn query_with_proof(
        &self,
        maybe_post_state: Option<Digest>,
        base_key: Key,
        path: &[String],
    ) -> Result<(StoredValue, Vec<TrieMerkleProof<Key, StoredValue>>), String> {
        let post_state = maybe_post_state
            .or(self.post_state_hash)
            .expect("builder must have a post-state hash");

        let path_vec: Vec<String> = path.to_vec();

        let query_request = QueryRequest::new(post_state, base_key, path_vec);

        let query_result = self
            .engine_state
            .run_query(CorrelationId::new(), query_request)
            .expect("should get query response");

        if let QueryResult::Success { value, proofs } = query_result {
            return Ok((value.deref().clone(), proofs));
        }

        panic! {"{:?}", query_result};
    }

    /// Queries for the total supply of token.
    /// # Panics
    /// Panics if the total supply can't be found.
    pub fn total_supply(&self, maybe_post_state: Option<Digest>) -> U512 {
        let mint_key: Key = self
            .get_system_contract_hash(MINT)
            .cloned()
            .expect("should have mint_contract_hash")
            .into();

        let result = self.query(maybe_post_state, mint_key, &[TOTAL_SUPPLY_KEY.to_string()]);

        let total_supply: U512 = if let Ok(StoredValue::CLValue(total_supply)) = result {
            total_supply.into_t().expect("total supply should be U512")
        } else {
            panic!("mint should track total supply");
        };

        total_supply
    }

    /// Queries for the base round reward.
    /// # Panics
    /// Panics if the total supply or seigniorage rate can't be found.
    pub fn base_round_reward(&mut self, maybe_post_state: Option<Digest>) -> U512 {
        let mint_key: Key = self.get_mint_contract_hash().into();

        let mint_contract = self
            .query(maybe_post_state, mint_key, &[])
            .expect("must get mint stored value")
            .as_contract()
            .expect("must convert to mint contract")
            .clone();

        let mint_named_keys = mint_contract.named_keys().clone();

        let total_supply_uref = *mint_named_keys
            .get(TOTAL_SUPPLY_KEY)
            .expect("must track total supply")
            .as_uref()
            .expect("must get uref");

        let round_seigniorage_rate_uref = *mint_named_keys
            .get(ROUND_SEIGNIORAGE_RATE_KEY)
            .expect("must track round seigniorage rate");

        let total_supply = self
            .query(maybe_post_state, Key::URef(total_supply_uref), &[])
            .expect("must read value under total supply URef")
            .as_cl_value()
            .expect("must convert into CL value")
            .clone()
            .into_t::<U512>()
            .expect("must convert into U512");

        let rate = self
            .query(maybe_post_state, round_seigniorage_rate_uref, &[])
            .expect("must read value")
            .as_cl_value()
            .expect("must conver to cl value")
            .clone()
            .into_t::<Ratio<U512>>()
            .expect("must conver to ratio");

        rate.checked_mul(&Ratio::from(total_supply))
            .map(|ratio| ratio.to_integer())
            .expect("must get base round reward")
    }

    /// Runs an [`ExecuteRequest`].
    pub fn exec(&mut self, exec_request: ExecuteRequest) -> &mut Self {
        self.try_exec(exec_request).expect("should execute")
    }

    /// Tries to run an [`ExecuteRequest`].
    pub fn try_exec(&mut self, mut exec_request: ExecuteRequest) -> Result<&mut Self, Error> {
        let exec_request = {
            let hash = self.post_state_hash.expect("expected post_state_hash");
            exec_request.parent_state_hash = hash;
            exec_request
        };

        let execution_results = self
            .engine_state
            .run_execute(CorrelationId::new(), exec_request)?;
        // Cache transformations
        self.transforms.extend(
            execution_results
                .iter()
                .map(|res| res.execution_journal().clone()),
        );
        self.exec_results
            .push(execution_results.into_iter().map(Rc::new).collect());
        Ok(self)
    }

    /// Commit effects of previous exec call on the latest post-state hash.
    pub fn commit(&mut self) -> &mut Self {
        let prestate_hash = self.post_state_hash.expect("Should have genesis hash");

        let effects = self.transforms.last().cloned().unwrap_or_default();

        self.commit_transforms(prestate_hash, effects.into())
    }

    /// Runs a commit request, expects a successful response, and
    /// overwrites existing cached post state hash with a new one.
    pub fn commit_transforms(
        &mut self,
        pre_state_hash: Digest,
        effects: AdditiveMap<Key, Transform>,
    ) -> &mut Self {
        let post_state_hash = self
            .engine_state
            .apply_effect(CorrelationId::new(), pre_state_hash, effects)
            .expect("should commit");
        self.post_state_hash = Some(post_state_hash);
        self
    }

    /// Upgrades the execution engine.
    /// Deprecated - this path does not use the scratch trie and generates many interstitial commits
    /// on upgrade.
    pub fn upgrade_with_upgrade_request(
        &mut self,
        engine_config: EngineConfig,
        upgrade_config: &mut UpgradeConfig,
    ) -> &mut Self {
        self.upgrade_with_upgrade_request_and_config(Some(engine_config), upgrade_config)
    }

    /// Upgrades the execution engine.
    ///
    /// If `engine_config` is set to None, then it is defaulted to the current one.
    pub fn upgrade_with_upgrade_request_and_config(
        &mut self,
        engine_config: Option<EngineConfig>,
        upgrade_config: &mut UpgradeConfig,
    ) -> &mut Self {
        let engine_config = engine_config.unwrap_or_else(|| self.engine_state.config().clone());

        let pre_state_hash = self.post_state_hash.expect("should have state hash");
        upgrade_config.with_pre_state_hash(pre_state_hash);

        let engine_state_mut =
            Rc::get_mut(&mut self.engine_state).expect("should have unique ownership");
        engine_state_mut.update_config(engine_config);

        let result = engine_state_mut.commit_upgrade(CorrelationId::new(), upgrade_config.clone());

        if let Ok(UpgradeSuccess {
            post_state_hash,
            execution_effect: _,
        }) = result
        {
            self.post_state_hash = Some(post_state_hash);
            self.system_contract_registry =
                self.query_system_contract_registry(Some(post_state_hash));
        }

        self.upgrade_results.push(result);
        self
    }

    /// Executes a request to call the system auction contract.
    pub fn run_auction(
        &mut self,
        era_end_timestamp_millis: u64,
        evicted_validators: Vec<PublicKey>,
    ) -> &mut Self {
        let auction = self.get_auction_contract_hash();
        let run_request = ExecuteRequestBuilder::contract_call_by_hash(
            *SYSTEM_ADDR,
            auction,
            METHOD_RUN_AUCTION,
            runtime_args! {
                ARG_ERA_END_TIMESTAMP_MILLIS => era_end_timestamp_millis,
                ARG_EVICTED_VALIDATORS => evicted_validators,
            },
        )
        .build();
        self.exec(run_request).commit().expect_success()
    }

    /// Increments engine state.
    pub fn step(&mut self, step_request: StepRequest) -> Result<StepSuccess, StepError> {
        let step_result = self
            .engine_state
            .commit_step(CorrelationId::new(), step_request);

        if let Ok(StepSuccess {
            post_state_hash, ..
        }) = &step_result
        {
            self.post_state_hash = Some(*post_state_hash);
        }

        step_result
    }

    /// Expects a successful run
    pub fn expect_success(&mut self) -> &mut Self {
        // Check first result, as only first result is interesting for a simple test
        let exec_results = self
            .get_last_exec_results()
            .expect("Expected to be called after run()");
        let exec_result = exec_results
            .get(0)
            .expect("Unable to get first deploy result");

        if exec_result.is_failure() {
            panic!(
                "Expected successful execution result, but instead got: {:#?}",
                exec_result,
            );
        }
        self
    }

    /// Expects a failed run
    pub fn expect_failure(&mut self) -> &mut Self {
        // Check first result, as only first result is interesting for a simple test
        let exec_results = self
            .get_last_exec_results()
            .expect("Expected to be called after run()");
        let exec_result = exec_results
            .get(0)
            .expect("Unable to get first deploy result");

        if exec_result.is_success() {
            panic!(
                "Expected failed execution result, but instead got: {:?}",
                exec_result,
            );
        }

        self
    }

    /// Returns `true` if the las exec had an error, otherwise returns false.
    pub fn is_error(&self) -> bool {
        self.get_last_exec_results()
            .expect("Expected to be called after run()")
            .get(0)
            .expect("Unable to get first execution result")
            .is_failure()
    }

    /// Returns an `Option<engine_state::Error>` if the last exec had an error.
    pub fn get_error(&self) -> Option<engine_state::Error> {
        self.get_last_exec_results()
            .expect("Expected to be called after run()")
            .get(0)
            .expect("Unable to get first deploy result")
            .as_error()
            .cloned()
    }

    /// Gets `ExecutionJournal`s of all passed runs.
    pub fn get_execution_journals(&self) -> Vec<ExecutionJournal> {
        self.transforms.clone()
    }

    /// Gets genesis account (if present)
    pub fn get_genesis_account(&self) -> &Account {
        self.system_account
            .as_ref()
            .expect("Unable to obtain genesis account. Please run genesis first.")
    }

    /// Returns the [`ContractHash`] of the mint, panics if it can't be found.
    pub fn get_mint_contract_hash(&self) -> ContractHash {
        self.get_system_contract_hash(MINT)
            .cloned()
            .expect("Unable to obtain mint contract. Please run genesis first.")
    }

    /// Returns the [`ContractHash`] of the "handle payment" contract, panics if it can't be found.
    pub fn get_handle_payment_contract_hash(&self) -> ContractHash {
        self.get_system_contract_hash(HANDLE_PAYMENT)
            .cloned()
            .expect("Unable to obtain handle payment contract. Please run genesis first.")
    }

    /// Returns the [`ContractHash`] of the "standard payment" contract, panics if it can't be
    /// found.
    pub fn get_standard_payment_contract_hash(&self) -> ContractHash {
        self.get_system_contract_hash(STANDARD_PAYMENT)
            .cloned()
            .expect("Unable to obtain standard payment contract. Please run genesis first.")
    }

    fn get_system_contract_hash(&self, contract_name: &str) -> Option<&ContractHash> {
        self.system_contract_registry
            .as_ref()
            .and_then(|registry| registry.get(contract_name))
    }

    /// Returns the [`ContractHash`] of the "auction" contract, panics if it can't be found.
    pub fn get_auction_contract_hash(&self) -> ContractHash {
        self.get_system_contract_hash(AUCTION)
            .cloned()
            .expect("Unable to obtain auction contract. Please run genesis first.")
    }

    /// Returns genesis transforms, panics if there aren't any.
    pub fn get_genesis_transforms(&self) -> &AdditiveMap<Key, Transform> {
        self.genesis_transforms
            .as_ref()
            .expect("should have genesis transforms")
    }

    /// Returns the genesis hash, panics if it can't be found.
    pub fn get_genesis_hash(&self) -> Digest {
        self.genesis_hash
            .expect("Genesis hash should be present. Should be called after run_genesis.")
    }

    /// Returns the post state hash, panics if it can't be found.
    pub fn get_post_state_hash(&self) -> Digest {
        self.post_state_hash.expect("Should have post-state hash.")
    }

    /// Returns the engine state.
    pub fn get_engine_state(&self) -> &EngineState<S> {
        &self.engine_state
    }

    /// Returns the last results execs.
    pub fn get_last_exec_results(&self) -> Option<Vec<Rc<ExecutionResult>>> {
        let exec_results = self.exec_results.last()?;

        Some(exec_results.iter().map(Rc::clone).collect())
    }

    /// Returns the owned results of a specific exec.
    pub fn get_exec_result_owned(&self, index: usize) -> Option<Vec<Rc<ExecutionResult>>> {
        let exec_results = self.exec_results.get(index)?;

        Some(exec_results.iter().map(Rc::clone).collect())
    }

    /// Returns a count of exec results.
    pub fn get_exec_results_count(&self) -> usize {
        self.exec_results.len()
    }

    /// Returns a `Result` containing an [`UpgradeSuccess`].
    pub fn get_upgrade_result(
        &self,
        index: usize,
    ) -> Option<&Result<UpgradeSuccess, engine_state::Error>> {
        self.upgrade_results.get(index)
    }

    /// Expects upgrade success.
    pub fn expect_upgrade_success(&mut self) -> &mut Self {
        // Check first result, as only first result is interesting for a simple test
        let result = self
            .upgrade_results
            .last()
            .expect("Expected to be called after a system upgrade.")
            .as_ref();

        result.unwrap_or_else(|_| panic!("Expected success, got: {:?}", result));

        self
    }

    /// Returns the "handle payment" contract, panics if it can't be found.
    pub fn get_handle_payment_contract(&self) -> Contract {
        let handle_payment_contract: Key = self
            .get_system_contract_hash(HANDLE_PAYMENT)
            .cloned()
            .expect("should have handle payment contract uref")
            .into();
        self.query(None, handle_payment_contract, &[])
            .and_then(|v| v.try_into().map_err(|error| format!("{:?}", error)))
            .expect("should find handle payment URef")
    }

    /// Returns the balance of a purse, panics if the balance can't be parsed into a `U512`.
    pub fn get_purse_balance(&self, purse: URef) -> U512 {
        let base_key = Key::Balance(purse.addr());
        self.query(None, base_key, &[])
            .and_then(|v| CLValue::try_from(v).map_err(|error| format!("{:?}", error)))
            .and_then(|cl_value| cl_value.into_t().map_err(|error| format!("{:?}", error)))
            .expect("should parse balance into a U512")
    }

    /// Returns a `BalanceResult` for a purse, panics if the balance can't be found.
    pub fn get_purse_balance_result(&self, purse: URef) -> BalanceResult {
        let correlation_id = CorrelationId::new();
        let state_root_hash: Digest = self.post_state_hash.expect("should have post_state_hash");
        self.engine_state
            .get_purse_balance(correlation_id, state_root_hash, purse)
            .expect("should get purse balance")
    }

    /// Returns a `BalanceResult` for a purse using a `PublicKey`.
    pub fn get_public_key_balance_result(&self, public_key: PublicKey) -> BalanceResult {
        let correlation_id = CorrelationId::new();
        let state_root_hash: Digest = self.post_state_hash.expect("should have post_state_hash");
        self.engine_state
            .get_balance(correlation_id, state_root_hash, public_key)
            .expect("should get purse balance using public key")
    }

    /// Gets the purse balance of a proposer.
    pub fn get_proposer_purse_balance(&self) -> U512 {
        let proposer_account = self
            .get_account(*DEFAULT_PROPOSER_ADDR)
            .expect("proposer account should exist");
        self.get_purse_balance(proposer_account.main_purse())
    }

    /// Queries for an `Account`.
    pub fn get_account(&self, account_hash: AccountHash) -> Option<Account> {
        match self.query(None, Key::Account(account_hash), &[]) {
            Ok(account_value) => match account_value {
                StoredValue::Account(account) => Some(account),
                _ => None,
            },
            Err(_) => None,
        }
    }

    /// Queries for an `Account` and panics if it can't be found.
    pub fn get_expected_account(&self, account_hash: AccountHash) -> Account {
        self.get_account(account_hash).expect("account to exist")
    }

    /// Queries for a contract by `ContractHash`.
    pub fn get_contract(&self, contract_hash: ContractHash) -> Option<Contract> {
        let contract_value: StoredValue = self
            .query(None, contract_hash.into(), &[])
            .expect("should have contract value");

        if let StoredValue::Contract(contract) = contract_value {
            Some(contract)
        } else {
            None
        }
    }

    /// Queries for a contract by `ContractHash` and returns an `Option<ContractWasm>`.
    pub fn get_contract_wasm(&self, contract_hash: ContractHash) -> Option<ContractWasm> {
        let contract_value: StoredValue = self
            .query(None, contract_hash.into(), &[])
            .expect("should have contract value");

        if let StoredValue::ContractWasm(contract_wasm) = contract_value {
            Some(contract_wasm)
        } else {
            None
        }
    }

    /// Queries for a contract package by `ContractPackageHash`.
    pub fn get_contract_package(
        &self,
        contract_package_hash: ContractPackageHash,
    ) -> Option<ContractPackage> {
        let contract_value: StoredValue = self
            .query(None, contract_package_hash.into(), &[])
            .expect("should have package value");

        if let StoredValue::ContractPackage(package) = contract_value {
            Some(package)
        } else {
            None
        }
    }

    /// Queries for a transfer by `TransferAddr`.
    pub fn get_transfer(&self, transfer: TransferAddr) -> Option<Transfer> {
        let transfer_value: StoredValue = self
            .query(None, Key::Transfer(transfer), &[])
            .expect("should have transfer value");

        if let StoredValue::Transfer(transfer) = transfer_value {
            Some(transfer)
        } else {
            None
        }
    }

    /// Queries for deploy info by `DeployHash`.
    pub fn get_deploy_info(&self, deploy_hash: DeployHash) -> Option<DeployInfo> {
        let deploy_info_value: StoredValue = self
            .query(None, Key::DeployInfo(deploy_hash), &[])
            .expect("should have deploy info value");

        if let StoredValue::DeployInfo(deploy_info) = deploy_info_value {
            Some(deploy_info)
        } else {
            None
        }
    }

    /// Returns a `Vec<Gas>` representing execution consts.
    pub fn exec_costs(&self, index: usize) -> Vec<Gas> {
        let exec_results = self
            .get_exec_result_owned(index)
            .expect("should have exec response");
        utils::get_exec_costs(exec_results)
    }

    /// Returns the `Gas` cost of the last exec.
    pub fn last_exec_gas_cost(&self) -> Gas {
        let exec_results = self
            .get_last_exec_results()
            .expect("Expected to be called after run()");
        let exec_result = exec_results.get(0).expect("should have result");
        exec_result.cost()
    }

    /// Returns the result of the last exec.
    pub fn last_exec_result(&self) -> &ExecutionResult {
        let exec_results = self
            .exec_results
            .last()
            .expect("Expected to be called after run()");
        exec_results.get(0).expect("should have result").as_ref()
    }

    /// Assert that last error is the expected one.
    ///
    /// NOTE: we're using string-based representation for checking equality
    /// as the `Error` type does not implement `Eq` (many of its subvariants don't).
    pub fn assert_error(&self, expected_error: Error) {
        match self.get_error() {
            Some(error) => assert_eq!(format!("{:?}", expected_error), format!("{:?}", error)),
            None => panic!("expected error ({:?}) got success", expected_error),
        }
    }

    /// Returns the error message of the last exec.
    pub fn exec_error_message(&self, index: usize) -> Option<String> {
        let response = self.get_exec_result_owned(index)?;
        Some(utils::get_error_message(response))
    }

    /// Gets [`EraValidators`].
    pub fn get_era_validators(&mut self) -> EraValidators {
        let correlation_id = CorrelationId::new();
        let state_hash = self.get_post_state_hash();
        let request = GetEraValidatorsRequest::new(state_hash, *DEFAULT_PROTOCOL_VERSION);
        let system_contract_registry = self
            .system_contract_registry
            .clone()
            .expect("System contract registry not found. Please run genesis first.");
        self.engine_state
            .get_era_validators(correlation_id, Some(system_contract_registry), request)
            .expect("get era validators should not error")
    }

    /// Gets [`ValidatorWeights`] for a given [`EraId`].
    pub fn get_validator_weights(&mut self, era_id: EraId) -> Option<ValidatorWeights> {
        let mut result = self.get_era_validators();
        result.remove(&era_id)
    }

    /// Gets [`Bids`].
    pub fn get_bids(&mut self) -> Bids {
        let get_bids_request = GetBidsRequest::new(self.get_post_state_hash());

        let get_bids_result = self
            .engine_state
            .get_bids(CorrelationId::new(), get_bids_request)
            .unwrap();

        get_bids_result.into_success().unwrap()
    }

    /// Gets [`UnbondingPurses`].
    pub fn get_unbonds(&mut self) -> UnbondingPurses {
        let correlation_id = CorrelationId::new();
        let state_root_hash = self.get_post_state_hash();

        let tracking_copy = self
            .engine_state
            .tracking_copy(state_root_hash)
            .unwrap()
            .unwrap();

        let reader = tracking_copy.reader();

        let unbond_keys = reader
            .keys_with_prefix(correlation_id, &[KeyTag::Unbond as u8])
            .unwrap_or_default();

        let mut ret = BTreeMap::new();

        for key in unbond_keys.into_iter() {
            let read_result = reader.read(correlation_id, &key);
            if let (Key::Unbond(account_hash), Ok(Some(StoredValue::Unbonding(unbonding_purses)))) =
                (key, read_result)
            {
                ret.insert(account_hash, unbonding_purses);
            }
        }

        ret
    }

    /// Gets [`WithdrawPurses`].
    pub fn get_withdraw_purses(&mut self) -> WithdrawPurses {
        let correlation_id = CorrelationId::new();
        let state_root_hash = self.get_post_state_hash();

        let tracking_copy = self
            .engine_state
            .tracking_copy(state_root_hash)
            .unwrap()
            .unwrap();

        let reader = tracking_copy.reader();

        let withdraws_keys = reader
            .keys_with_prefix(correlation_id, &[KeyTag::Withdraw as u8])
            .unwrap_or_default();

        let mut ret = BTreeMap::new();

        for key in withdraws_keys.into_iter() {
            let read_result = reader.read(correlation_id, &key);
            if let (Key::Withdraw(account_hash), Ok(Some(StoredValue::Withdraw(withdraw_purses)))) =
                (key, read_result)
            {
                ret.insert(account_hash, withdraw_purses);
            }
        }

        ret
    }

    /// Gets all `[Key::Balance]`s in global state.
    pub fn get_balance_keys(&self) -> Vec<Key> {
        self.get_keys(KeyTag::Balance).unwrap_or_default()
    }

    /// Gets all keys in global state by a prefix.
    pub fn get_keys(&self, tag: KeyTag) -> Result<Vec<Key>, S::Error> {
        let correlation_id = CorrelationId::new();
        let state_root_hash = self.get_post_state_hash();

        let tracking_copy = self
            .engine_state
            .tracking_copy(state_root_hash)
            .unwrap()
            .unwrap();

        let reader = tracking_copy.reader();

        reader.keys_with_prefix(correlation_id, &[tag as u8])
    }

    /// Gets a stored value from a contract's named keys.
    pub fn get_value<T>(&mut self, contract_hash: ContractHash, name: &str) -> T
    where
        T: FromBytes + CLTyped,
    {
        let contract = self
            .get_contract(contract_hash)
            .expect("should have contract");
        let key = contract
            .named_keys()
            .get(name)
            .expect("should have named key");
        let stored_value = self.query(None, *key, &[]).expect("should query");
        let cl_value = stored_value
            .as_cl_value()
            .cloned()
            .expect("should be cl value");
        let result: T = cl_value.into_t().expect("should convert");
        result
    }

    /// Gets an [`EraId`].
    pub fn get_era(&mut self) -> EraId {
        let auction_contract = self.get_auction_contract_hash();
        self.get_value(auction_contract, ERA_ID_KEY)
    }

    /// Gets the auction delay.
    pub fn get_auction_delay(&mut self) -> u64 {
        let auction_contract = self.get_auction_contract_hash();
        self.get_value(auction_contract, AUCTION_DELAY_KEY)
    }

    /// Gets the unbonding delay
    pub fn get_unbonding_delay(&mut self) -> u64 {
        let auction_contract = self.get_auction_contract_hash();
        self.get_value(auction_contract, UNBONDING_DELAY_KEY)
    }

    /// Gets the [`ContractHash`] of the system auction contract, panics if it can't be found.
    pub fn get_system_auction_hash(&self) -> ContractHash {
        let correlation_id = CorrelationId::new();
        let state_root_hash = self.get_post_state_hash();
        self.engine_state
            .get_system_auction_hash(correlation_id, state_root_hash)
            .expect("should have auction hash")
    }

    /// Gets the [`ContractHash`] of the system mint contract, panics if it can't be found.
    pub fn get_system_mint_hash(&self) -> ContractHash {
        let correlation_id = CorrelationId::new();
        let state_root_hash = self.get_post_state_hash();
        self.engine_state
            .get_system_mint_hash(correlation_id, state_root_hash)
            .expect("should have auction hash")
    }

    /// Gets the [`ContractHash`] of the system handle payment contract, panics if it can't be
    /// found.
    pub fn get_system_handle_payment_hash(&self) -> ContractHash {
        let correlation_id = CorrelationId::new();
        let state_root_hash = self.get_post_state_hash();
        self.engine_state
            .get_handle_payment_hash(correlation_id, state_root_hash)
            .expect("should have handle payment hash")
    }

    /// Returns the [`ContractHash`] of the system standard payment contract, panics if it can't be
    /// found.
    pub fn get_system_standard_payment_hash(&self) -> ContractHash {
        let correlation_id = CorrelationId::new();
        let state_root_hash = self.get_post_state_hash();
        self.engine_state
            .get_standard_payment_hash(correlation_id, state_root_hash)
            .expect("should have standard payment hash")
    }

    /// Resets the `exec_results`, `upgrade_results` and `transform` fields.
    pub fn clear_results(&mut self) -> &mut Self {
        self.exec_results = Vec::new();
        self.upgrade_results = Vec::new();
        self.transforms = Vec::new();
        self
    }

    /// Advances eras by num_eras
    pub fn advance_eras_by(
        &mut self,
        num_eras: u64,
        reward_items: impl IntoIterator<Item = RewardItem>,
        evict_items: impl IntoIterator<Item = EvictItem>,
    ) {
        let step_request_builder = StepRequestBuilder::new()
            .with_protocol_version(ProtocolVersion::V1_0_0)
            .with_reward_items(reward_items)
            .with_evict_items(evict_items)
            .with_run_auction(true);

        for _ in 0..num_eras {
            let step_request = step_request_builder
                .clone()
                .with_parent_state_hash(self.get_post_state_hash())
                .with_next_era_id(self.get_era().successor())
                .build();

            self.step(step_request)
                .expect("failed to execute step request");
        }
    }

    /// Advances eras by configured amount
    pub fn advance_eras_by_default_auction_delay(
        &mut self,
        reward_items: impl IntoIterator<Item = RewardItem>,
        evict_items: impl IntoIterator<Item = EvictItem>,
    ) {
        let auction_delay = self.get_auction_delay();
        self.advance_eras_by(auction_delay + 1, reward_items, evict_items);
    }

    /// Advances by a single era.
    pub fn advance_era(
        &mut self,
        reward_items: impl IntoIterator<Item = RewardItem>,
        evict_items: impl IntoIterator<Item = EvictItem>,
    ) {
        self.advance_eras_by(1, reward_items, evict_items);
    }

    /// Returns a trie by hash.
    pub fn get_trie(&mut self, state_hash: Digest) -> Option<Trie<Key, StoredValue>> {
        self.engine_state
            .get_trie_full(CorrelationId::default(), state_hash)
            .unwrap()
            .map(|bytes| bytesrepr::deserialize(bytes.into_inner().into()).unwrap())
    }

    /// Returns the costs related to interacting with the auction system contract.
    pub fn get_auction_costs(&self) -> AuctionCosts {
        *self.engine_state.config().system_config().auction_costs()
    }

    /// Returns the costs related to interacting with the mint system contract.
    pub fn get_mint_costs(&self) -> MintCosts {
        *self.engine_state.config().system_config().mint_costs()
    }

    /// Returns the costs related to interacting with the handle payment system contract.
    pub fn get_handle_payment_costs(&self) -> HandlePaymentCosts {
        *self
            .engine_state
            .config()
            .system_config()
            .handle_payment_costs()
    }

    /// Commits a prune of leaf nodes from the tip of the merkle trie.
    pub fn commit_prune(&mut self, prune_config: PruneConfig) -> &mut Self {
        let result = self
            .engine_state
            .commit_prune(CorrelationId::new(), prune_config);

        if let Ok(PruneResult::Success { post_state_hash }) = &result {
            self.post_state_hash = Some(*post_state_hash);
        }

        self.prune_results.push(result);
        self
    }

    /// Returns a `Result` containing a [`PruneResult`].
    pub fn get_prune_result(
        &self,
        index: usize,
    ) -> Option<&Result<PruneResult, engine_state::Error>> {
        self.prune_results.get(index)
    }

    /// Expects a prune success.
    pub fn expect_prune_success(&mut self) -> &mut Self {
        // Check first result, as only first result is interesting for a simple test
        let result = self
            .prune_results
            .last()
            .expect("Expected to be called after a system upgrade.")
            .as_ref();

        let prune_result = result.unwrap_or_else(|_| panic!("Expected success, got: {:?}", result));
        match prune_result {
            PruneResult::RootNotFound => panic!("Root not found"),
            PruneResult::DoesNotExist => panic!("Does not exists"),
            PruneResult::Success { .. } => {}
        }

        self
    }

    /// Gets the transform map that's cached between runs
    #[deprecated(
        since = "2.1.0",
        note = "Use `get_execution_journals` that returns transforms in the order they were created."
    )]
    pub fn get_transforms(&self) -> Vec<AdditiveMap<Key, Transform>> {
        self.transforms
            .clone()
            .into_iter()
            .map(|journal| journal.into_iter().collect())
            .collect()
    }

    /// Returns the results of all execs.
    #[deprecated(
        since = "2.3.0",
        note = "use `get_last_exec_results` or `get_exec_result_owned` instead"
    )]
    pub fn get_exec_results(&self) -> &Vec<Vec<Rc<ExecutionResult>>> {
        &self.exec_results
    }

    /// Returns the results of a specific exec.
    #[deprecated(since = "2.3.0", note = "use `get_exec_result_owned` instead")]
    pub fn get_exec_result(&self, index: usize) -> Option<&Vec<Rc<ExecutionResult>>> {
        self.exec_results.get(index)
    }

    /// Gets [`UnbondingPurses`].
    #[deprecated(since = "2.3.0", note = "use `get_withdraw_purses` instead")]
    pub fn get_withdraws(&mut self) -> UnbondingPurses {
        let withdraw_purses = self.get_withdraw_purses();
        let unbonding_purses: UnbondingPurses = withdraw_purses
            .iter()
            .map(|(key, withdraw_purse)| {
                (
                    key.to_owned(),
                    withdraw_purse
                        .iter()
                        .map(|withdraw_purse| withdraw_purse.to_owned().into())
                        .collect::<Vec<UnbondingPurse>>(),
                )
            })
            .collect::<BTreeMap<AccountHash, Vec<UnbondingPurse>>>();
        unbonding_purses
    }

    /// Calculates refunded amount from a last execution request.
    pub fn calculate_refund_amount(&self, payment_amount: U512) -> U512 {
        let gas_amount = Motes::from_gas(self.last_exec_gas_cost(), DEFAULT_GAS_PRICE)
            .expect("should create motes from gas");

        let refund_ratio = match self.engine_state.config().refund_handling() {
            RefundHandling::Refund { refund_ratio } | RefundHandling::Burn { refund_ratio } => {
                *refund_ratio
            }
        };

        let (numer, denom) = refund_ratio.into();
        let refund_ratio = Ratio::new_raw(U512::from(numer), U512::from(denom));

        // amount declared to be paid in payment code MINUS gas spent in last execution.
        let refundable_amount = Ratio::from(payment_amount) - Ratio::from(gas_amount.value());
        (refundable_amount * refund_ratio).to_integer()
    }
}