radix-engine 1.3.1

Reference implementation of Radix Engine, from the Radix DLT project.
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
use super::*;
use crate::blueprints::consensus_manager::EpochChangeEvent;
use crate::errors::*;
use crate::internal_prelude::*;
use crate::kernel::kernel_callback_api::ExecutionReceipt;
use crate::system::system_db_reader::SystemDatabaseReader;
use crate::system::system_modules::costing::*;
use crate::system::system_modules::execution_trace::*;
use crate::system::system_substate_schemas::*;
use crate::transaction::SystemStructure;
use colored::*;
use radix_engine_interface::blueprints::transaction_processor::InstructionOutput;
use radix_transactions::prelude::*;
use sbor::representations::*;

/// This type is not intended to be encoded or have a consistent scrypto encoding.
/// Some of the parts of it are encoded in the node, but not the receipt itself.
#[derive(Clone, PartialEq, Eq)]
pub struct TransactionReceipt {
    /// Costing parameters
    pub costing_parameters: CostingParameters,
    /// Transaction costing parameters
    pub transaction_costing_parameters: TransactionCostingParametersReceiptV2,
    /// Transaction fee summary
    pub fee_summary: TransactionFeeSummary,
    /// Transaction fee detail
    /// Available if `ExecutionConfig::enable_cost_breakdown` is enabled
    pub fee_details: Option<TransactionFeeDetails>,
    /// Transaction result
    pub result: TransactionResult,
    /// Hardware resources usage report
    /// Available if `resources_usage` feature flag is enabled
    pub resources_usage: Option<ResourcesUsage>,
    /// This field contains debug information about the transaction which is extracted during the
    /// transaction execution.
    pub debug_information: Option<TransactionDebugInformation>,
}

// Type for backwards compatibility to avoid integrator compile errors
// when they update.
pub type TransactionReceiptV1 = TransactionReceipt;

#[cfg(all(feature = "std", feature = "flamegraph"))]
impl TransactionReceipt {
    pub fn generate_execution_breakdown_flamegraph_svg_bytes(
        &self,
        title: impl AsRef<str>,
        network_definition: &NetworkDefinition,
    ) -> Result<Vec<u8>, FlamegraphError> {
        let title = title.as_ref();

        // The options to use when constructing the flamechart.
        let mut opts = inferno::flamegraph::Options::default();
        "Execution Cost Units".clone_into(&mut opts.count_name);
        opts.title = title.to_owned();

        // Transforming the detailed execution cost breakdown into a string understood by the flamegraph
        // library.
        let Some(TransactionDebugInformation {
            ref detailed_execution_cost_breakdown,
            ..
        }) = self.debug_information
        else {
            return Err(FlamegraphError::DetailedCostBreakdownNotAvailable);
        };

        let flamegraph_string = Self::transform_detailed_execution_breakdown_into_flamegraph_string(
            detailed_execution_cost_breakdown,
            network_definition,
        );

        // Writing the flamegraph string to a temporary file since its required by the flamegraph lib to
        // have a path.
        let result = {
            let tempfile = tempfile::NamedTempFile::new().map_err(FlamegraphError::IOError)?;
            std::fs::write(&tempfile, flamegraph_string).map_err(FlamegraphError::IOError)?;

            let mut result = std::io::Cursor::new(Vec::new());
            inferno::flamegraph::from_files(&mut opts, &[tempfile.path().to_owned()], &mut result)
                .map_err(|_| FlamegraphError::CreationError)?;

            result.set_position(0);
            result.into_inner()
        };

        Ok(result)
    }

    fn transform_detailed_execution_breakdown_into_flamegraph_string(
        detailed_execution_cost_breakdown: &[DetailedExecutionCostBreakdownEntry],
        network_definition: &NetworkDefinition,
    ) -> String {
        // Putting use in here so it doesn't cause unused import compile warning in no-std
        use crate::system::actor::*;

        let address_bech32m_encoder = AddressBech32Encoder::new(network_definition);

        let mut lines = Vec::<String>::new();
        let mut path_stack = vec![];
        for (
            index,
            DetailedExecutionCostBreakdownEntry {
                item: execution_item,
                ..
            },
        ) in detailed_execution_cost_breakdown.iter().enumerate()
        {
            // Constructing the full path
            match execution_item {
                ExecutionCostBreakdownItem::Invocation { actor, .. } => {
                    let actor_string = match actor {
                        Actor::Root => "root".to_owned(),
                        Actor::Method(MethodActor {
                            node_id,
                            ref ident,
                            ref object_info,
                            ..
                        }) => {
                            format!(
                                "Method <{}>::{}::{}",
                                address_bech32m_encoder
                                    .encode(node_id.as_bytes())
                                    .expect("Encoding of an address can't fail"),
                                object_info.blueprint_info.blueprint_id.blueprint_name,
                                ident
                            )
                        }
                        Actor::Function(FunctionActor {
                            ref blueprint_id,
                            ref ident,
                            ..
                        }) => {
                            format!(
                                "Function <{}>::{}::{}",
                                address_bech32m_encoder
                                    .encode(blueprint_id.package_address.as_bytes())
                                    .expect("Encoding of an address can't fail"),
                                blueprint_id.blueprint_name,
                                ident
                            )
                        }
                        Actor::BlueprintHook(BlueprintHookActor {
                            hook,
                            ref blueprint_id,
                            ..
                        }) => {
                            format!(
                                "Blueprint Hook <{}>::{}::{:?}",
                                address_bech32m_encoder
                                    .encode(blueprint_id.package_address.as_bytes())
                                    .expect("Encoding of an address can't fail"),
                                blueprint_id.blueprint_name,
                                hook
                            )
                        }
                    };
                    path_stack.push(format!("Invocation: {actor_string} ({index})"))
                }
                ExecutionCostBreakdownItem::InvocationComplete => {
                    path_stack.pop();
                }
                ExecutionCostBreakdownItem::Execution {
                    simple_name,
                    cost_units,
                    ..
                } => {
                    lines.push(format!(
                        "{}{}({}) {}",
                        if path_stack.join(";").is_empty() {
                            "".to_owned()
                        } else {
                            format!("{};", path_stack.join(";"))
                        },
                        simple_name,
                        index,
                        cost_units
                    ));
                }
            }
        }

        lines.join("\n")
    }
}

impl ExecutionReceipt for TransactionReceipt {
    fn set_resource_usage(&mut self, resources_usage: ResourcesUsage) {
        self.resources_usage = Some(resources_usage);
    }
}

#[derive(Default, Debug, Clone, ScryptoSbor, PartialEq, Eq)]
pub struct TransactionFeeSummary {
    /// Total execution cost units consumed.
    pub total_execution_cost_units_consumed: u32,
    /// Total finalization cost units consumed.
    pub total_finalization_cost_units_consumed: u32,

    /// Total execution cost in XRD.
    pub total_execution_cost_in_xrd: Decimal,
    /// Total finalization cost in XRD.
    pub total_finalization_cost_in_xrd: Decimal,
    /// Total tipping cost in XRD.
    pub total_tipping_cost_in_xrd: Decimal,
    /// Total storage cost in XRD.
    pub total_storage_cost_in_xrd: Decimal,
    /// Total royalty cost in XRD.
    pub total_royalty_cost_in_xrd: Decimal,
}

#[derive(Default, Debug, Clone, ScryptoSbor, PartialEq, Eq)]
pub struct TransactionFeeDetails {
    /// Execution cost breakdown
    pub execution_cost_breakdown: BTreeMap<String, u32>,
    /// Finalization cost breakdown
    pub finalization_cost_breakdown: BTreeMap<String, u32>,
}

/// Captures whether a transaction should be committed, and its other results
#[derive(Debug, Clone, ScryptoSbor, PartialEq, Eq)]
#[allow(clippy::large_enum_variant)]
pub enum TransactionResult {
    Commit(CommitResult),
    Reject(RejectResult),
    Abort(AbortResult),
}

#[derive(Debug, Clone, ScryptoSbor, PartialEq, Eq)]
pub struct CommitResult {
    /// Substate updates
    pub state_updates: StateUpdates,
    /// Information extracted from the substate updates
    pub state_update_summary: StateUpdateSummary,
    /// The source of transaction fee
    pub fee_source: FeeSource,
    /// The destination of transaction fee
    pub fee_destination: FeeDestination,
    /// Transaction execution outcome
    pub outcome: TransactionOutcome,
    /// Events emitted
    pub application_events: Vec<(EventTypeIdentifier, Vec<u8>)>,
    /// Logs emitted
    pub application_logs: Vec<(Level, String)>,
    /// Additional annotation on substates and events
    pub system_structure: SystemStructure,
    /// Transaction execution traces
    /// Available if `ExecutionTrace` module is enabled
    pub execution_trace: Option<TransactionExecutionTrace>,
    /// The actually performed nullifications.
    /// For example, a failed transaction won't include subintent nullifications.
    pub performed_nullifications: Vec<Nullification>,
}

#[derive(Debug, Clone, Default, ScryptoSbor, PartialEq, Eq)]
pub struct FeeSource {
    pub paying_vaults: IndexMap<NodeId, Decimal>,
}

#[derive(Debug, Clone, Default, ScryptoSbor, PartialEq, Eq)]
pub struct FeeDestination {
    pub to_proposer: Decimal,
    pub to_validator_set: Decimal,
    pub to_burn: Decimal,
    pub to_royalty_recipients: IndexMap<RoyaltyRecipient, Decimal>,
}

/// Captures whether a transaction's commit outcome is Success or Failure
#[derive(Debug, Clone, ScryptoSbor, PartialEq, Eq)]
pub enum TransactionOutcome {
    Success(Vec<InstructionOutput>),
    Failure(RuntimeError),
}

#[derive(Debug, Clone, ScryptoSbor, Default, PartialEq, Eq)]
pub struct TransactionExecutionTrace {
    pub execution_traces: Vec<ExecutionTrace>,
    pub resource_changes: IndexMap<usize, Vec<ResourceChange>>,
    pub fee_locks: FeeLocks,
}

#[derive(Debug, Clone, Eq, PartialEq, ScryptoSbor, Default)]
pub struct FeeLocks {
    pub lock: Decimal,
    pub contingent_lock: Decimal,
}

#[derive(Debug, Copy, Clone, Eq, PartialEq, ScryptoSbor)]
pub enum Nullification {
    Intent {
        expiry_epoch: Epoch,
        intent_hash: IntentHash,
    },
}

impl Nullification {
    pub fn of_intent(
        intent_hash_nullification: IntentHashNullification,
        current_epoch: Epoch,
        is_success: bool,
    ) -> Option<Self> {
        let (intent_hash, expiry_epoch) = match intent_hash_nullification {
            IntentHashNullification::TransactionIntent {
                intent_hash,
                expiry_epoch,
            } => (intent_hash.into(), expiry_epoch),
            IntentHashNullification::SimulatedTransactionIntent { simulated } => {
                let intent_hash = simulated.transaction_intent_hash();
                let expiry_epoch = simulated.expiry_epoch(current_epoch);
                (intent_hash.into(), expiry_epoch)
            }
            IntentHashNullification::Subintent {
                intent_hash: subintent_hash,
                expiry_epoch,
            } => {
                // Don't write subintent nullification on failure.
                // Subintents can't pay fees, so this isn't abusable.
                if !is_success {
                    return None;
                }
                (subintent_hash.into(), expiry_epoch)
            }
            IntentHashNullification::SimulatedSubintent { simulated } => {
                if !is_success {
                    return None;
                }
                let subintent_hash = simulated.subintent_hash();
                let expiry_epoch = simulated.expiry_epoch(current_epoch);
                (subintent_hash.into(), expiry_epoch)
            }
        };
        Some(Nullification::Intent {
            expiry_epoch,
            intent_hash,
        })
    }

    pub fn transaction_tracker_keys(self) -> (Epoch, Hash) {
        match self {
            Nullification::Intent {
                expiry_epoch,
                intent_hash,
            } => (expiry_epoch, intent_hash.into_hash()),
        }
    }
}

#[derive(Debug, Clone, ScryptoSbor, PartialEq, Eq)]
pub struct RejectResult {
    pub reason: RejectionReason,
}

#[derive(Debug, Clone, ScryptoSbor, PartialEq, Eq)]
pub struct AbortResult {
    pub reason: AbortReason,
}

#[derive(Debug, Clone, Display, PartialEq, Eq, Sbor)]
pub enum AbortReason {
    ConfiguredAbortTriggeredOnFeeLoanRepayment,
}

#[derive(Debug, Clone, Default, ScryptoSbor, PartialEq, Eq)]
pub struct ResourcesUsage {
    pub heap_allocations_sum: usize,
    pub heap_peak_memory: usize,
    pub cpu_cycles: u64,
}

/// A structure of debug information about the transaction execution.
///
/// This is intentionally not SBOR codable since we never want this data to be persisted or
/// transmitted over the wire.
#[derive(Clone, PartialEq, Eq)]
pub struct TransactionDebugInformation {
    /* Costing Breakdown */
    /// A detailed trace of where execution cost units were consumed.
    pub detailed_execution_cost_breakdown: Vec<DetailedExecutionCostBreakdownEntry>,
}

impl TransactionExecutionTrace {
    pub fn worktop_changes(&self) -> IndexMap<usize, Vec<WorktopChange>> {
        let mut aggregator = index_map_new::<usize, Vec<WorktopChange>>();
        for trace in &self.execution_traces {
            trace.worktop_changes(&mut aggregator)
        }
        aggregator
    }
}

impl TransactionResult {
    pub fn is_commit_success(&self) -> bool {
        match self {
            TransactionResult::Commit(c) => matches!(c.outcome, TransactionOutcome::Success(_)),
            _ => false,
        }
    }
}

impl CommitResult {
    pub fn empty_with_outcome(outcome: TransactionOutcome) -> Self {
        Self {
            state_updates: Default::default(),
            state_update_summary: Default::default(),
            fee_source: Default::default(),
            fee_destination: Default::default(),
            outcome,
            application_events: Default::default(),
            application_logs: Default::default(),
            system_structure: Default::default(),
            execution_trace: Default::default(),
            performed_nullifications: Default::default(),
        }
    }

    pub fn next_epoch(&self) -> Option<EpochChangeEvent> {
        // Note: Node should use a well-known index id
        for (ref event_type_id, ref event_data) in self.application_events.iter() {
            let is_consensus_manager = match &event_type_id.0 {
                Emitter::Method(node_id, ModuleId::Main)
                    if node_id.entity_type() == Some(EntityType::GlobalConsensusManager) =>
                {
                    true
                }
                Emitter::Function(blueprint_id)
                    if blueprint_id.package_address.eq(&CONSENSUS_MANAGER_PACKAGE) =>
                {
                    true
                }
                _ => false,
            };

            if is_consensus_manager {
                if let Ok(epoch_change_event) = scrypto_decode::<EpochChangeEvent>(event_data) {
                    return Some(epoch_change_event);
                }
            }
        }
        None
    }

    pub fn new_package_addresses(&self) -> &IndexSet<PackageAddress> {
        &self.state_update_summary.new_packages
    }

    pub fn new_component_addresses(&self) -> &IndexSet<ComponentAddress> {
        &self.state_update_summary.new_components
    }

    pub fn new_resource_addresses(&self) -> &IndexSet<ResourceAddress> {
        &self.state_update_summary.new_resources
    }

    pub fn new_vault_addresses(&self) -> &IndexSet<InternalAddress> {
        &self.state_update_summary.new_vaults
    }

    pub fn vault_balance_changes(&self) -> &IndexMap<NodeId, (ResourceAddress, BalanceChange)> {
        &self.state_update_summary.vault_balance_changes
    }

    pub fn output<T: ScryptoDecode>(&self, nth: usize) -> T {
        match &self.outcome {
            TransactionOutcome::Success(o) => match o.get(nth) {
                Some(InstructionOutput::CallReturn(value)) => {
                    scrypto_decode::<T>(value).expect("Output can't be converted")
                }
                _ => panic!("No output for [{}]", nth),
            },
            TransactionOutcome::Failure(_) => panic!("Transaction failed"),
        }
    }
}

impl TransactionOutcome {
    pub fn is_success(&self) -> bool {
        matches!(self, Self::Success(_))
    }

    pub fn expect_success(&self) -> &Vec<InstructionOutput> {
        match self {
            TransactionOutcome::Success(results) => results,
            TransactionOutcome::Failure(error) => panic!("Outcome was a failure: {error:?}"),
        }
    }

    pub fn expect_failure(&self) -> &RuntimeError {
        match self {
            TransactionOutcome::Success(_) => panic!("Outcome was an unexpected success"),
            TransactionOutcome::Failure(error) => error,
        }
    }

    pub fn success_or_else<E, F: Fn(&RuntimeError) -> E>(
        &self,
        f: F,
    ) -> Result<&Vec<InstructionOutput>, E> {
        match self {
            TransactionOutcome::Success(results) => Ok(results),
            TransactionOutcome::Failure(error) => Err(f(error)),
        }
    }
}

impl TransactionReceipt {
    /// An empty receipt for merging changes into.
    pub fn empty_with_commit(commit_result: CommitResult) -> Self {
        Self {
            costing_parameters: CostingParameters::babylon_genesis(),
            transaction_costing_parameters: Default::default(),
            fee_summary: Default::default(),
            fee_details: Default::default(),
            result: TransactionResult::Commit(commit_result),
            resources_usage: Default::default(),
            debug_information: Default::default(),
        }
    }

    pub fn empty_commit_success() -> Self {
        Self::empty_with_commit(CommitResult::empty_with_outcome(
            TransactionOutcome::Success(vec![]),
        ))
    }

    pub fn is_commit_success(&self) -> bool {
        matches!(
            self.result,
            TransactionResult::Commit(CommitResult {
                outcome: TransactionOutcome::Success(_),
                ..
            })
        )
    }

    pub fn is_commit_failure(&self) -> bool {
        matches!(
            self.result,
            TransactionResult::Commit(CommitResult {
                outcome: TransactionOutcome::Failure(_),
                ..
            })
        )
    }

    pub fn is_rejection(&self) -> bool {
        matches!(self.result, TransactionResult::Reject(_))
    }

    pub fn expect_commit_ignore_outcome(&self) -> &CommitResult {
        match &self.result {
            TransactionResult::Commit(c) => c,
            TransactionResult::Reject(e) => panic!("Transaction was rejected: {:?}", e),
            TransactionResult::Abort(_) => panic!("Transaction was aborted"),
        }
    }

    pub fn into_commit_ignore_outcome(self) -> CommitResult {
        match self.result {
            TransactionResult::Commit(c) => c,
            TransactionResult::Reject(e) => panic!("Transaction was rejected: {:?}", e),
            TransactionResult::Abort(_) => panic!("Transaction was aborted"),
        }
    }

    pub fn expect_commit(&self, success: bool) -> &CommitResult {
        let c = self.expect_commit_ignore_outcome();
        if c.outcome.is_success() != success {
            panic!(
                "Expected {} but was {}: {:?}",
                if success { "success" } else { "failure" },
                if c.outcome.is_success() {
                    "success"
                } else {
                    "failure"
                },
                c.outcome
            )
        }
        c
    }

    pub fn expect_commit_success(&self) -> &CommitResult {
        self.expect_commit(true)
    }

    pub fn expect_commit_failure(&self) -> &CommitResult {
        self.expect_commit(false)
    }

    pub fn expect_commit_failure_containing_error(&self, error_needle: &str) {
        let error_message = self
            .expect_commit_failure()
            .outcome
            .expect_failure()
            .to_string(NO_NETWORK);
        assert!(
            error_message.contains(error_needle),
            "{error_needle:?} was not contained in RuntimeError: {error_message}"
        );
    }

    pub fn expect_rejection(&self) -> &RejectionReason {
        match &self.result {
            TransactionResult::Commit(..) => panic!("Expected rejection but was commit"),
            TransactionResult::Reject(ref r) => &r.reason,
            TransactionResult::Abort(..) => panic!("Expected rejection but was abort"),
        }
    }

    pub fn expect_rejection_containing_error(&self, error_needle: &str) {
        let error_message = self.expect_rejection().to_string(NO_NETWORK);
        assert!(
            error_message.contains(error_needle),
            "{error_needle:?} was not contained in RejectionReason"
        );
    }

    pub fn expect_abortion(&self) -> &AbortReason {
        match &self.result {
            TransactionResult::Commit(..) => panic!("Expected abortion but was commit"),
            TransactionResult::Reject(..) => panic!("Expected abortion but was reject"),
            TransactionResult::Abort(ref r) => &r.reason,
        }
    }

    pub fn expect_not_success(&self) {
        match &self.result {
            TransactionResult::Commit(c) => {
                if c.outcome.is_success() {
                    panic!("Transaction succeeded unexpectedly")
                }
            }
            TransactionResult::Reject(..) => {}
            TransactionResult::Abort(..) => {}
        }
    }

    pub fn expect_specific_rejection<F>(&self, f: F)
    where
        F: Fn(&RejectionReason) -> bool,
    {
        match &self.result {
            TransactionResult::Commit(..) => panic!("Expected rejection but was committed"),
            TransactionResult::Reject(result) => {
                if !f(&result.reason) {
                    panic!(
                        "Expected specific rejection but was different error:\n{:?}",
                        self
                    );
                }
            }
            TransactionResult::Abort(..) => panic!("Expected rejection but was abort"),
        }
    }

    pub fn expect_failure(&self) -> &RuntimeError {
        match &self.result {
            TransactionResult::Commit(c) => match &c.outcome {
                TransactionOutcome::Success(_) => panic!("Expected failure but was success"),
                TransactionOutcome::Failure(error) => error,
            },
            TransactionResult::Reject(_) => panic!("Transaction was rejected"),
            TransactionResult::Abort(..) => panic!("Transaction was aborted"),
        }
    }

    pub fn expect_specific_failure<F>(&self, f: F)
    where
        F: Fn(&RuntimeError) -> bool,
    {
        if !f(self.expect_failure()) {
            panic!(
                "Expected specific failure but was different error:\n{:?}",
                self
            );
        }
    }

    pub fn expect_auth_failure(&self) {
        self.expect_specific_failure(|e| {
            matches!(
                e,
                RuntimeError::SystemModuleError(SystemModuleError::AuthError(..))
            )
        })
    }

    pub fn expect_auth_assertion_failure(&self) {
        self.expect_specific_failure(|e| {
            matches!(
                e,
                RuntimeError::SystemError(SystemError::AssertAccessRuleFailed)
            )
        })
    }

    pub fn effective_execution_cost_unit_price(&self) -> Decimal {
        // Below unwraps are safe, no chance to overflow considering current costing parameters
        self.costing_parameters
            .execution_cost_unit_price
            .checked_mul(
                Decimal::ONE
                    .checked_add(self.transaction_costing_parameters.tip_proportion)
                    .unwrap(),
            )
            .unwrap()
    }

    pub fn effective_finalization_cost_unit_price(&self) -> Decimal {
        let one_percent = Decimal::ONE_HUNDREDTH;

        // Below unwraps are safe, no chance to overflow considering current costing parameters
        self.costing_parameters
            .finalization_cost_unit_price
            .checked_mul(
                Decimal::ONE
                    .checked_add(
                        one_percent
                            .checked_mul(self.transaction_costing_parameters.tip_proportion)
                            .unwrap(),
                    )
                    .unwrap(),
            )
            .unwrap()
    }
}

macro_rules! prefix {
    ($i:expr, $list:expr) => {
        if $i == $list.len() - 1 {
            "└─"
        } else {
            "├─"
        }
    };
}

impl fmt::Debug for TransactionReceipt {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{}",
            self.display(TransactionReceiptDisplayContext::default())
        )
    }
}

pub struct TransactionReceiptDisplayContext<'a> {
    pub encoder: Option<&'a AddressBech32Encoder>,
    pub system_database_reader: Option<SystemDatabaseReader<'a, dyn SubstateDatabase + 'a>>,
    pub display_state_updates: bool,
    pub use_ansi_colors: bool,
    pub max_substate_length_to_display: usize,
}

impl<'a> Default for TransactionReceiptDisplayContext<'a> {
    fn default() -> Self {
        Self {
            encoder: None,
            system_database_reader: None,
            display_state_updates: true,
            use_ansi_colors: true,
            max_substate_length_to_display: 1024,
        }
    }
}

impl<'a> TransactionReceiptDisplayContext<'a> {
    pub fn display_context(&self) -> ScryptoValueDisplayContext<'a> {
        ScryptoValueDisplayContext::with_optional_bech32(self.encoder)
    }

    pub fn address_display_context(&self) -> AddressDisplayContext<'a> {
        AddressDisplayContext {
            encoder: self.encoder,
        }
    }

    pub fn max_substate_length_to_display(&self) -> usize {
        self.max_substate_length_to_display
    }

    pub fn lookup_schema<T: AsRef<NodeId>>(
        &self,
        full_type_id: &FullyScopedTypeId<T>,
    ) -> Option<(LocalTypeId, Rc<VersionedScryptoSchema>)> {
        self.system_database_reader.as_ref().map(|system_reader| {
            let schema = system_reader
                .get_schema(full_type_id.0.as_ref(), &full_type_id.1)
                .unwrap();

            (full_type_id.2, schema)
        })
    }

    fn format_first_top_level_title_with_detail<F: fmt::Write, D: fmt::Display>(
        &self,
        f: &mut F,
        title: &str,
        detail: D,
    ) -> Result<(), fmt::Error> {
        if self.use_ansi_colors {
            write!(f, "{} {}", format!("{}:", title).bold().green(), detail)
        } else {
            write!(f, "{}: {}", title.to_uppercase(), detail)
        }
    }

    fn format_top_level_title_with_detail<F: fmt::Write, D: fmt::Display>(
        &self,
        f: &mut F,
        title: &str,
        detail: D,
    ) -> Result<(), fmt::Error> {
        if self.use_ansi_colors {
            write!(f, "\n{} {}", format!("{}:", title).bold().green(), detail)
        } else {
            write!(f, "\n\n{}: {}", title.to_uppercase(), detail)
        }
    }

    fn display_title(&self, title: &str) -> MaybeAnsi {
        if self.use_ansi_colors {
            MaybeAnsi::Ansi(title.bold().green())
        } else {
            MaybeAnsi::Normal(title.to_string())
        }
    }

    fn display_result(&self, result: &TransactionResult) -> MaybeAnsi {
        let (string, format): (String, fn(String) -> ColoredString) = match result {
            TransactionResult::Commit(c) => match &c.outcome {
                TransactionOutcome::Success(_) => ("COMMITTED SUCCESS".to_string(), |x| x.green()),
                TransactionOutcome::Failure(e) => (
                    format!("COMMITTED FAILURE: {}", e.display(self.display_context())),
                    |x| x.red(),
                ),
            },
            TransactionResult::Reject(r) => (
                format!("REJECTED: {}", r.reason.display(self.display_context())),
                |x| x.red(),
            ),
            TransactionResult::Abort(a) => (format!("ABORTED: {}", a.reason), |x| x.bright_red()),
        };
        if self.use_ansi_colors {
            MaybeAnsi::Ansi(format(string))
        } else {
            MaybeAnsi::Normal(string)
        }
    }

    fn display_log(&self, level: &Level, message: &str) -> (MaybeAnsi, MaybeAnsi) {
        let (level, format): (_, fn(&str) -> ColoredString) = match level {
            Level::Error => ("ERROR", |x| x.red()),
            Level::Warn => ("WARN", |x| x.yellow()),
            Level::Info => ("INFO", |x| x.green()),
            Level::Debug => ("DEBUG", |x| x.cyan()),
            Level::Trace => ("TRACE", |x| x.normal()),
        };

        if self.use_ansi_colors {
            (
                MaybeAnsi::Ansi(format(level)),
                MaybeAnsi::Ansi(format(message)),
            )
        } else {
            (
                MaybeAnsi::Normal(level.to_string()),
                MaybeAnsi::Normal(message.to_string()),
            )
        }
    }
}

enum MaybeAnsi {
    Ansi(ColoredString),
    Normal(String),
}

impl fmt::Display for MaybeAnsi {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            MaybeAnsi::Ansi(value) => write!(f, "{}", value),
            MaybeAnsi::Normal(value) => write!(f, "{}", value),
        }
    }
}

impl<'a> From<&'a AddressBech32Encoder> for TransactionReceiptDisplayContext<'a> {
    fn from(encoder: &'a AddressBech32Encoder) -> Self {
        Self {
            encoder: Some(encoder),
            ..Default::default()
        }
    }
}

impl<'a> From<Option<&'a AddressBech32Encoder>> for TransactionReceiptDisplayContext<'a> {
    fn from(encoder: Option<&'a AddressBech32Encoder>) -> Self {
        Self {
            encoder,
            ..Default::default()
        }
    }
}

pub struct TransactionReceiptDisplayContextBuilder<'a>(TransactionReceiptDisplayContext<'a>);

impl<'a> TransactionReceiptDisplayContextBuilder<'a> {
    pub fn new() -> Self {
        Self(Default::default())
    }

    pub fn encoder(mut self, encoder: &'a AddressBech32Encoder) -> Self {
        self.0.encoder = Some(encoder);
        self
    }

    pub fn schema_lookup_from_db(mut self, db: &'a dyn SubstateDatabase) -> Self {
        self.0.system_database_reader = Some(SystemDatabaseReader::new(db));
        self
    }

    pub fn display_state_updates(mut self, setting: bool) -> Self {
        self.0.display_state_updates = setting;
        self
    }

    pub fn use_ansi_colors(mut self, setting: bool) -> Self {
        self.0.use_ansi_colors = setting;
        self
    }

    pub fn set_max_substate_length_to_display(mut self, setting: usize) -> Self {
        self.0.max_substate_length_to_display = setting;
        self
    }

    pub fn build(self) -> TransactionReceiptDisplayContext<'a> {
        self.0
    }
}

impl<'a> Default for TransactionReceiptDisplayContextBuilder<'a> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a> ContextualDisplay<TransactionReceiptDisplayContext<'a>> for TransactionReceipt {
    type Error = fmt::Error;

    fn contextual_format(
        &self,
        f: &mut fmt::Formatter,
        context: &TransactionReceiptDisplayContext<'a>,
    ) -> Result<(), Self::Error> {
        let result = &self.result;
        let scrypto_value_display_context = context.display_context();
        let address_display_context = context.address_display_context();

        context.format_first_top_level_title_with_detail(
            f,
            "Transaction Status",
            context.display_result(result),
        )?;

        context.format_top_level_title_with_detail(
            f,
            "Transaction Cost",
            format!("{} XRD", self.fee_summary.total_cost()),
        )?;
        write!(
            f,
            "\n├─ {} {} XRD, {} execution cost units",
            context.display_title("Network execution:"),
            self.fee_summary.total_execution_cost_in_xrd,
            self.fee_summary.total_execution_cost_units_consumed,
        )?;
        write!(
            f,
            "\n├─ {} {} XRD, {} finalization cost units",
            context.display_title("Network finalization:"),
            self.fee_summary.total_finalization_cost_in_xrd,
            self.fee_summary.total_finalization_cost_units_consumed,
        )?;
        write!(
            f,
            "\n├─ {} {} XRD",
            context.display_title("Tip:"),
            self.fee_summary.total_tipping_cost_in_xrd
        )?;
        write!(
            f,
            "\n├─ {} {} XRD",
            context.display_title("Network Storage:"),
            self.fee_summary.total_storage_cost_in_xrd
        )?;
        write!(
            f,
            "\n└─ {} {} XRD",
            context.display_title("Royalties:"),
            self.fee_summary.total_royalty_cost_in_xrd
        )?;

        if let TransactionResult::Commit(c) = &result {
            context.format_top_level_title_with_detail(f, "Logs", c.application_logs.len())?;
            for (i, (level, msg)) in c.application_logs.iter().enumerate() {
                let (level, msg) = context.display_log(level, msg);
                write!(
                    f,
                    "\n{} [{:5}] {}",
                    prefix!(i, c.application_logs),
                    level,
                    msg
                )?;
            }

            context.format_top_level_title_with_detail(f, "Events", c.application_events.len())?;
            for (i, (event_type_identifier, event_data)) in c.application_events.iter().enumerate()
            {
                display_event(
                    f,
                    prefix!(i, c.application_events),
                    event_type_identifier,
                    &c.system_structure,
                    event_data,
                    context,
                )?;
            }

            if context.display_state_updates {
                (&c.state_updates, &c.system_structure).contextual_format(f, context)?;
            }

            if let TransactionOutcome::Success(outputs) = &c.outcome {
                context.format_top_level_title_with_detail(f, "Outputs", outputs.len())?;
                for (i, output) in outputs.iter().enumerate() {
                    write!(
                        f,
                        "\n{} {}",
                        prefix!(i, outputs),
                        match output {
                            InstructionOutput::CallReturn(x) => IndexedScryptoValue::from_slice(x)
                                .expect("Impossible case! Instruction output can't be decoded")
                                .to_string(ValueDisplayParameters::Schemaless {
                                    display_mode: DisplayMode::RustLike(RustLikeOptions::full()),
                                    print_mode: PrintMode::MultiLine {
                                        indent_size: 2,
                                        base_indent: 3,
                                        first_line_indent: 0
                                    },
                                    custom_context: scrypto_value_display_context,
                                    depth_limit: SCRYPTO_SBOR_V1_MAX_DEPTH
                                }),
                            InstructionOutput::None => "None".to_string(),
                        }
                    )?;
                }
            }

            let balance_changes = c.vault_balance_changes();
            context.format_top_level_title_with_detail(
                f,
                "Balance Changes",
                balance_changes.len(),
            )?;
            for (i, (vault_id, (resource, delta))) in balance_changes.iter().enumerate() {
                write!(
                    f,
                    // NB - we use ResAddr instead of Resource to protect people who read new resources as
                    //      `Resource: ` from the receipts (see eg resim.sh)
                    "\n{} Vault: {}\n   ResAddr: {}\n   Change: {}",
                    prefix!(i, balance_changes),
                    vault_id.display(address_display_context),
                    resource.display(address_display_context),
                    match delta {
                        BalanceChange::Fungible(d) => format!("{}", d),
                        BalanceChange::NonFungible { added, removed } => {
                            format!("+{:?}, -{:?}", added, removed)
                        }
                    }
                )?;
            }

            context.format_top_level_title_with_detail(
                f,
                "New Entities",
                c.new_package_addresses().len()
                    + c.new_component_addresses().len()
                    + c.new_resource_addresses().len(),
            )?;
            for (i, package_address) in c.new_package_addresses().iter().enumerate() {
                write!(
                    f,
                    "\n{} Package: {}",
                    prefix!(i, c.new_package_addresses()),
                    package_address.display(address_display_context)
                )?;
            }
            for (i, component_address) in c.new_component_addresses().iter().enumerate() {
                write!(
                    f,
                    "\n{} Component: {}",
                    prefix!(i, c.new_component_addresses()),
                    component_address.display(address_display_context)
                )?;
            }
            for (i, resource_address) in c.new_resource_addresses().iter().enumerate() {
                write!(
                    f,
                    "\n{} Resource: {}",
                    prefix!(i, c.new_resource_addresses()),
                    resource_address.display(address_display_context)
                )?;
            }
        }

        Ok(())
    }
}

impl<'a, 'b> ContextualDisplay<TransactionReceiptDisplayContext<'a>>
    for (&'b StateUpdates, &'b SystemStructure)
{
    type Error = fmt::Error;

    fn contextual_format(
        &self,
        f: &mut fmt::Formatter,
        context: &TransactionReceiptDisplayContext<'a>,
    ) -> Result<(), Self::Error> {
        let state_updates = self.0;
        let system_structure = self.1;
        context.format_top_level_title_with_detail(
            f,
            "State Updates",
            format!(
                "{} {}",
                state_updates.by_node.len(),
                if state_updates.by_node.len() == 1 {
                    "entity"
                } else {
                    "entities"
                },
            ),
        )?;
        for (i, (node_id, node_updates)) in state_updates.by_node.iter().enumerate() {
            let by_partition = match node_updates {
                NodeStateUpdates::Delta { by_partition } => by_partition,
            };
            write!(
                f,
                "\n{} {} across {} partitions",
                prefix!(i, state_updates.by_node),
                node_id.display(context.address_display_context()),
                by_partition.len(),
            )?;

            for (j, (partition_number, partition_updates)) in by_partition.iter().enumerate() {
                // NOTE: This could be improved by mapping partition numbers back to a system-focused name
                //       This would require either adding partition descriptions into SystemStructure, or
                //       having some inverse entity-type specific descriptors.
                match partition_updates {
                    PartitionStateUpdates::Delta { by_substate } => {
                        write!(
                            f,
                            "\n  {} Partition({}): {} {}",
                            prefix!(j, by_partition),
                            partition_number.0,
                            by_substate.len(),
                            if by_substate.len() == 1 {
                                "change"
                            } else {
                                "changes"
                            },
                        )?;
                        for (k, (substate_key, update)) in by_substate.iter().enumerate() {
                            display_substate_change(
                                f,
                                prefix!(k, by_substate),
                                system_structure,
                                context,
                                node_id,
                                partition_number,
                                substate_key,
                                update.as_ref(),
                            )?;
                        }
                    }
                    PartitionStateUpdates::Batch(BatchPartitionStateUpdate::Reset {
                        new_substate_values,
                    }) => {
                        write!(
                            f,
                            "\n {} Partition({}): RESET ({} new values)",
                            prefix!(j, by_partition),
                            partition_number.0,
                            new_substate_values.len()
                        )?;
                        for (k, (substate_key, value)) in new_substate_values.iter().enumerate() {
                            display_substate_change(
                                f,
                                prefix!(k, new_substate_values),
                                system_structure,
                                context,
                                node_id,
                                partition_number,
                                substate_key,
                                DatabaseUpdateRef::Set(value),
                            )?;
                        }
                    }
                }
            }
        }
        Ok(())
    }
}

#[allow(clippy::too_many_arguments)]
fn display_substate_change<'a, F: fmt::Write>(
    f: &mut F,
    prefix: &str,
    system_structure: &SystemStructure,
    receipt_context: &TransactionReceiptDisplayContext<'a>,
    node_id: &NodeId,
    partition_number: &PartitionNumber,
    substate_key: &SubstateKey,
    change: DatabaseUpdateRef,
) -> Result<(), fmt::Error> {
    let substate_structure = system_structure
        .substate_system_structures
        .get(node_id)
        .unwrap()
        .get(partition_number)
        .unwrap()
        .get(substate_key)
        .unwrap();
    match change {
        DatabaseUpdateRef::Set(substate_value) => {
            write!(f, "\n    {prefix} Set: ")?;
            format_receipt_substate_key(f, substate_structure, receipt_context, substate_key)?;
            write!(f, "\n       Value: ")?;
            format_receipt_substate_value(f, substate_structure, receipt_context, substate_value)?;
        }
        DatabaseUpdateRef::Delete => {
            write!(f, "\n    {prefix} Delete: ")?;
            format_receipt_substate_key(f, substate_structure, receipt_context, substate_key)?;
        }
    }
    Ok(())
}

fn format_receipt_substate_key<'a, F: fmt::Write>(
    f: &mut F,
    substate_structure: &SubstateSystemStructure,
    receipt_context: &TransactionReceiptDisplayContext<'a>,
    substate_key: &SubstateKey,
) -> Result<(), fmt::Error> {
    let print_mode = PrintMode::SingleLine;
    match substate_structure {
        SubstateSystemStructure::SystemField(structure) => {
            write!(f, "{:?}", structure.field_kind)
        }
        SubstateSystemStructure::SystemSchema => {
            let key_contents = substate_key.for_map().unwrap();
            let hash: SchemaHash = scrypto_decode(key_contents).unwrap();
            write!(f, "SchemaHash({})", hash.0)
        }
        SubstateSystemStructure::KeyValueStoreEntry(structure) => {
            let value = scrypto_decode(substate_key.for_map().unwrap()).unwrap();
            format_scrypto_value_with_full_type_id(
                f,
                print_mode,
                value,
                receipt_context,
                &structure.key_full_type_id,
            )
        }
        SubstateSystemStructure::ObjectField(_) => {
            let key_contents = substate_key.for_field().unwrap();
            write!(f, "Field({})", key_contents)
        }
        SubstateSystemStructure::ObjectKeyValuePartitionEntry(structure) => {
            let value = scrypto_decode(substate_key.for_map().unwrap()).unwrap();
            let full_type_id = extract_object_type_id(&structure.key_schema);
            format_scrypto_value_with_full_type_id(
                f,
                print_mode,
                value,
                receipt_context,
                &full_type_id,
            )
        }
        SubstateSystemStructure::ObjectIndexPartitionEntry(structure) => {
            let value = scrypto_decode(substate_key.for_map().unwrap()).unwrap();
            let full_type_id = extract_object_type_id(&structure.key_schema);
            format_scrypto_value_with_full_type_id(
                f,
                print_mode,
                value,
                receipt_context,
                &full_type_id,
            )
        }
        SubstateSystemStructure::ObjectSortedIndexPartitionEntry(structure) => {
            let (sort_bytes, key_contents) = substate_key.for_sorted().unwrap();
            let value = scrypto_decode(key_contents).unwrap();
            let full_type_id = extract_object_type_id(&structure.key_schema);
            write!(f, "SortKey({}, ", u16::from_be_bytes(*sort_bytes))?;
            format_scrypto_value_with_full_type_id(
                f,
                print_mode,
                value,
                receipt_context,
                &full_type_id,
            )?;
            write!(f, ")")
        }
    }
}

pub fn format_receipt_substate_value<'a, F: fmt::Write>(
    f: &mut F,
    substate_structure: &SubstateSystemStructure,
    receipt_context: &TransactionReceiptDisplayContext<'a>,
    substate_value: &[u8],
) -> Result<(), fmt::Error> {
    let print_mode = PrintMode::MultiLine {
        indent_size: 2,
        base_indent: 7,
        first_line_indent: 0,
    };
    if substate_value.len() > receipt_context.max_substate_length_to_display() {
        write!(
            f,
            "(Hidden as longer than {} bytes. Hash: {})",
            receipt_context.max_substate_length_to_display(),
            hash(substate_value)
        )
    } else {
        let (payload, full_type_id) = match substate_structure {
            SubstateSystemStructure::SystemField(structure) => {
                let single_type_schema = resolve_system_field_schema(structure.field_kind);
                let raw_value = scrypto_decode(substate_value).unwrap();
                return format_scrypto_value_with_schema(
                    f,
                    print_mode,
                    raw_value,
                    receipt_context,
                    &single_type_schema.schema,
                    single_type_schema.type_id,
                );
            }
            SubstateSystemStructure::SystemSchema => {
                let single_type_schema = resolve_system_schema_schema();
                let raw_value = scrypto_decode(substate_value).unwrap();
                return format_scrypto_value_with_schema(
                    f,
                    print_mode,
                    raw_value,
                    receipt_context,
                    &single_type_schema.schema,
                    single_type_schema.type_id,
                );
            }
            SubstateSystemStructure::KeyValueStoreEntry(structure) => {
                let payload =
                    scrypto_decode::<KeyValueEntrySubstate<ScryptoRawValue>>(substate_value)
                        .unwrap();
                (payload.into_value(), structure.value_full_type_id)
            }
            SubstateSystemStructure::ObjectField(structure) => {
                let payload =
                    scrypto_decode::<FieldSubstate<ScryptoRawValue>>(substate_value).unwrap();
                write_lock_status(f, payload.lock_status())?;
                (
                    Some(payload.into_payload()),
                    extract_object_type_id(&structure.value_schema),
                )
            }
            SubstateSystemStructure::ObjectKeyValuePartitionEntry(structure) => {
                let payload =
                    scrypto_decode::<KeyValueEntrySubstate<ScryptoRawValue>>(substate_value)
                        .unwrap();
                write_lock_status(f, payload.lock_status())?;
                (
                    payload.into_value(),
                    extract_object_type_id(&structure.value_schema),
                )
            }
            SubstateSystemStructure::ObjectIndexPartitionEntry(structure) => {
                let payload =
                    scrypto_decode::<IndexEntrySubstate<ScryptoRawValue>>(substate_value).unwrap();
                (
                    Some(payload.into_value()),
                    extract_object_type_id(&structure.value_schema),
                )
            }
            SubstateSystemStructure::ObjectSortedIndexPartitionEntry(structure) => {
                let payload =
                    scrypto_decode::<SortedIndexEntrySubstate<ScryptoRawValue>>(substate_value)
                        .unwrap();
                (
                    Some(payload.into_value()),
                    extract_object_type_id(&structure.value_schema),
                )
            }
        };
        match payload {
            Some(payload) => format_scrypto_value_with_full_type_id(
                f,
                print_mode,
                payload,
                receipt_context,
                &full_type_id,
            ),
            None => write!(f, "EMPTY"),
        }
    }
}

fn write_lock_status<F: fmt::Write>(f: &mut F, lock_status: LockStatus) -> Result<(), fmt::Error> {
    match lock_status {
        LockStatus::Unlocked => write!(f, "UNLOCKED "),
        LockStatus::Locked => write!(f, "LOCKED "),
    }
}

fn extract_object_type_id(structure: &ObjectSubstateTypeReference) -> FullyScopedTypeId<NodeId> {
    match structure {
        ObjectSubstateTypeReference::Package(r) => r.full_type_id.into_general(),
        ObjectSubstateTypeReference::ObjectInstance(r) => r.resolved_full_type_id,
    }
}

fn display_event<'a, F: fmt::Write>(
    f: &mut F,
    prefix: &str,
    event_type_identifier: &EventTypeIdentifier,
    system_structure: &SystemStructure,
    event_data: &[u8],
    receipt_context: &TransactionReceiptDisplayContext<'a>,
) -> Result<(), fmt::Error> {
    let event_system_structure = system_structure
        .event_system_structures
        .get(event_type_identifier)
        .expect("Expected event to appear in the system structure");

    let full_type_id = event_system_structure.package_type_reference.full_type_id;
    let schema_lookup = receipt_context.lookup_schema(&full_type_id);
    let emitter = &event_type_identifier.0;
    let print_mode = PrintMode::MultiLine {
        indent_size: 2,
        base_indent: 3,
        first_line_indent: 0,
    };
    let raw_value = scrypto_decode::<ScryptoRawValue>(event_data).unwrap();
    if schema_lookup.is_some() {
        write!(
            f,
            "\n{} Emitter: {}\n   Event: ",
            prefix,
            emitter.display(receipt_context.address_display_context()),
        )?;
        format_scrypto_value_with_full_type_id(
            f,
            print_mode,
            raw_value,
            receipt_context,
            &full_type_id,
        )?;
    } else {
        write!(
            f,
            "\n{} Emitter: {}\n   Name: {:?}\n   Data: ",
            prefix,
            emitter.display(receipt_context.address_display_context()),
            event_type_identifier.1,
        )?;
        format_scrypto_value_with_full_type_id(
            f,
            print_mode,
            raw_value,
            receipt_context,
            &full_type_id,
        )?;
    }
    Ok(())
}

fn format_scrypto_value_with_full_type_id<'a, F: fmt::Write, T: AsRef<NodeId>>(
    f: &mut F,
    print_mode: PrintMode,
    raw_value: ScryptoRawValue<'_>,
    receipt_context: &TransactionReceiptDisplayContext<'a>,
    full_type_id: &FullyScopedTypeId<T>,
) -> Result<(), fmt::Error> {
    let schema_lookup = receipt_context.lookup_schema(full_type_id);
    match schema_lookup {
        Some((local_type_id, schema)) => format_scrypto_value_with_schema(
            f,
            print_mode,
            raw_value,
            receipt_context,
            &schema,
            local_type_id,
        ),
        None => {
            let display_parameters: ValueDisplayParameters<'_, '_, ScryptoCustomExtension> =
                ValueDisplayParameters::Schemaless {
                    display_mode: DisplayMode::RustLike(RustLikeOptions::full()),
                    print_mode,
                    custom_context: receipt_context.display_context(),
                    depth_limit: SCRYPTO_SBOR_V1_MAX_DEPTH,
                };
            write!(f, "{}", raw_value.display(display_parameters))
        }
    }
}

fn format_scrypto_value_with_schema<'a, F: fmt::Write>(
    f: &mut F,
    print_mode: PrintMode,
    raw_value: ScryptoRawValue<'_>,
    receipt_context: &TransactionReceiptDisplayContext<'a>,
    schema: &VersionedScryptoSchema,
    local_type_id: LocalTypeId,
) -> Result<(), fmt::Error> {
    let display_parameters = ValueDisplayParameters::Annotated {
        display_mode: DisplayMode::RustLike(RustLikeOptions::full()),
        print_mode,
        custom_context: receipt_context.display_context(),
        schema: schema.v1(),
        type_id: local_type_id,
        depth_limit: SCRYPTO_SBOR_V1_MAX_DEPTH,
    };
    write!(f, "{}", raw_value.display(display_parameters))
}

impl From<FeeReserveFinalizationSummary> for TransactionFeeSummary {
    fn from(value: FeeReserveFinalizationSummary) -> Self {
        Self {
            total_execution_cost_units_consumed: value.total_execution_cost_units_consumed,
            total_finalization_cost_units_consumed: value.total_finalization_cost_units_consumed,
            total_execution_cost_in_xrd: value.total_execution_cost_in_xrd,
            total_finalization_cost_in_xrd: value.total_finalization_cost_in_xrd,
            total_tipping_cost_in_xrd: value.total_tipping_cost_in_xrd,
            total_storage_cost_in_xrd: value.total_storage_cost_in_xrd,
            total_royalty_cost_in_xrd: value.total_royalty_cost_in_xrd,
        }
    }
}

impl TransactionFeeSummary {
    pub fn total_cost(&self) -> Decimal {
        self.total_execution_cost_in_xrd
            .checked_add(self.total_finalization_cost_in_xrd)
            .unwrap()
            .checked_add(self.total_tipping_cost_in_xrd)
            .unwrap()
            .checked_add(self.total_storage_cost_in_xrd)
            .unwrap()
            .checked_add(self.total_royalty_cost_in_xrd)
            .unwrap()
    }

    pub fn network_fees(&self) -> Decimal {
        self.total_execution_cost_in_xrd
            .checked_add(self.total_finalization_cost_in_xrd)
            .unwrap()
            .checked_add(self.total_storage_cost_in_xrd)
            .unwrap()
    }

    //===================
    // For testing only
    //===================

    pub fn expected_reward_if_single_validator(&self) -> Decimal {
        self.expected_reward_as_proposer_if_single_validator()
            .checked_add(self.expected_reward_as_active_validator_if_single_validator())
            .unwrap()
    }

    pub fn expected_reward_as_proposer_if_single_validator(&self) -> Decimal {
        let one_percent = Decimal::ONE_HUNDREDTH;

        one_percent
            .checked_mul(TIPS_PROPOSER_SHARE_PERCENTAGE)
            .unwrap()
            .checked_mul(self.total_tipping_cost_in_xrd)
            .unwrap()
            .checked_add(
                one_percent
                    .checked_mul(NETWORK_FEES_PROPOSER_SHARE_PERCENTAGE)
                    .unwrap()
                    .checked_mul(
                        self.total_execution_cost_in_xrd
                            .checked_add(self.total_finalization_cost_in_xrd)
                            .unwrap()
                            .checked_add(self.total_storage_cost_in_xrd)
                            .unwrap(),
                    )
                    .unwrap(),
            )
            .unwrap()
    }

    pub fn expected_reward_as_active_validator_if_single_validator(&self) -> Decimal {
        let one_percent = Decimal::ONE_HUNDREDTH;

        one_percent
            .checked_mul(TIPS_VALIDATOR_SET_SHARE_PERCENTAGE)
            .unwrap()
            .checked_mul(self.total_tipping_cost_in_xrd)
            .unwrap()
            .checked_add(
                one_percent
                    .checked_mul(NETWORK_FEES_VALIDATOR_SET_SHARE_PERCENTAGE)
                    .unwrap()
                    .checked_mul(
                        self.total_execution_cost_in_xrd
                            .checked_add(self.total_finalization_cost_in_xrd)
                            .unwrap()
                            .checked_add(self.total_storage_cost_in_xrd)
                            .unwrap(),
                    )
                    .unwrap(),
            )
            .unwrap()
    }
}

#[cfg(feature = "std")]
#[derive(Debug)]
pub enum FlamegraphError {
    IOError(std::io::Error),
    CreationError,
    DetailedCostBreakdownNotAvailable,
}

#[cfg(test)]
mod tests {
    use radix_transactions::model::TransactionCostingParametersReceiptV2;

    use super::*;

    define_versioned!(
        #[derive(ScryptoSbor)]
        VersionedLocalTransactionExecution(LocalTransactionExecutionVersions) {
            previous_versions: [
                1 => LocalTransactionExecutionV1: { updates_to: 2 },
            ],
            latest_version: {
                2 => LocalTransactionExecution = LocalTransactionExecutionV2,
            },
        },
        outer_attributes: [
            // This is an effective copy of the contents of the local transaction execution store in the node.
            // This needs to be decodable!
            // By all means introduce _new versions_, with conversions between them,
            // and we can do the same in the node.
            // But this schema can't change, else we won't be able to decode existing executions in the node.
            // NOTE: This is just copied here to catch issues / changes earlier; an identical test exists in the node.
            #[derive(ScryptoSborAssertion)]
            #[sbor_assert(
                backwards_compatible(
                    bottlenose = "FILE:node_versioned_local_transaction_execution_bottlenose.bin",
                    cuttlefish = "FILE:node_versioned_local_transaction_execution_cuttlefish.bin"
                ),
                settings(allow_name_changes)
            )]
        ],
    );

    #[derive(ScryptoSbor)]
    struct LocalTransactionExecutionV1 {
        outcome: Result<(), ScryptoOwnedRawValue>,
        fee_summary: TransactionFeeSummary,
        fee_source: FeeSource,
        fee_destination: FeeDestination,
        engine_costing_parameters: CostingParameters,
        transaction_costing_parameters: TransactionCostingParametersReceiptV1,
        application_logs: Vec<(Level, String)>,
        state_update_summary: StateUpdateSummary,
        global_balance_summary: IndexMap<GlobalAddress, IndexMap<ResourceAddress, BalanceChange>>,
        substates_system_structure: Vec<SubstateSystemStructure>,
        events_system_structure: IndexMap<EventTypeIdentifier, EventSystemStructure>,
        next_epoch: Option<EpochChangeEvent>,
    }

    #[derive(ScryptoSbor)]
    struct LocalTransactionExecutionV2 {
        outcome: Result<(), PersistableRuntimeError>,
        fee_summary: TransactionFeeSummary,
        fee_source: FeeSource,
        fee_destination: FeeDestination,
        engine_costing_parameters: CostingParameters,
        transaction_costing_parameters: TransactionCostingParametersReceiptV2,
        application_logs: Vec<(Level, String)>,
        state_update_summary: StateUpdateSummary,
        global_balance_summary: IndexMap<GlobalAddress, IndexMap<ResourceAddress, BalanceChange>>,
        substates_system_structure: Vec<SubstateSystemStructure>,
        events_system_structure: IndexMap<EventTypeIdentifier, EventSystemStructure>,
        next_epoch: Option<EpochChangeEvent>,
    }

    impl From<LocalTransactionExecutionV1> for LocalTransactionExecutionV2 {
        fn from(value: LocalTransactionExecutionV1) -> Self {
            Self {
                outcome: value.outcome.map_err(|err| PersistableRuntimeError {
                    schema_index: 0,
                    encoded_error: err,
                }),
                fee_summary: value.fee_summary,
                fee_source: value.fee_source,
                fee_destination: value.fee_destination,
                engine_costing_parameters: value.engine_costing_parameters,
                transaction_costing_parameters: value.transaction_costing_parameters.into(),
                application_logs: value.application_logs,
                state_update_summary: value.state_update_summary,
                global_balance_summary: value.global_balance_summary,
                substates_system_structure: value.substates_system_structure,
                events_system_structure: value.events_system_structure,
                next_epoch: value.next_epoch,
            }
        }
    }
}