holofuel_types 0.1.0

Fuel types used for holofuel a mutual credit currency
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
//! The HoloFuel Fuel type and math functions, and JSON serialization support.  Supports Fraction
//! type for computing fractional HoloFuel amounts using rational numbers; useful for expressing
//! "percentages" of HoloFuel amounts without losing (too much) precision, while retaining the
//! ability to compute HoloFuel transaction fees on the largest possible transaction amounts.

use crate::error::FuelError;
use crate::fraction::Fraction;
use crate::time::Period;
use hdk::prelude::timestamp::Timestamp;
use regex::Regex;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use std::{
    collections::VecDeque,
    fmt,
    ops::{Add, AddAssign, Div, Mul, MulAssign, Neg, Sub, SubAssign},
    result,
    str::FromStr,
};
///
/// Fuel -- Account for Holo fuel, in fractions of 1/10^6 ( 1/1,000,000th of a unit)
///
/// Ensures that the integer amount never leaves Rust / Web Assembly.  For example, if the i128 value
/// was processed in Javascript, it must not exceed a +/- value that would fit into an IEEE 754
/// double-precision floating point value without loss of precision.  Thus, the no value exceeding
/// +/- 2^53-1 fractional units of Holo fuel should be converted into an f64.
///
/// This Fuel struct is what ensures that we do not pass numeric Holo fuel amounts through the WASM
/// boundary.  All precise Holo fuel values, such as 2,882,343,476 x 1/1e6 units of Holo Fuel are
/// represented as Display 'fmt()' values (eg. "2882.343467" Holo fuel).  The Display value is precisely
/// convertible back and forth into the internal integer representation without loss of precision,
/// and is also a human-readable fractional amount of Holo fuel, it is also the preferred external
/// representation.
///
/// Javascript (and other languages that use IEEE 754 floats to represent integer values) cannot be
/// allowed to compute numeric values that will exceed 2^53-1 (9.0072e15); the capacity of IEEE 754
/// mantissa w/o loss of numerical accuracy, for those platforms that emulate i128 using IEEE 754
/// double-precision floating point.  Allowing 15 total decimal digits in 7 integer and 8 fractional
/// digits (+/-1e15), and 13 hex digits (+/-4.5e15) is safely within this range.  However, we would
/// give up some possibly useful capacity.
///
/// The available range in [0,2^53), with 8 decimal digits after the decimal point, is about 7.95
/// digits: log( 2**53 / 10 ** 8, 10 ) == 7.9545.  So, we would allow up to 8 integer digits, and
/// manually check for precision overflow by comparing against 2**53, and rejecting any value that
/// exceeds the maximum 9.0071e15).  Likewise, we accept 14 hex digits, and check the full precision
/// limits manually.  This would allow only Holo fuel account and transaction values up to about
/// 90,071,992 Holo fuel; insufficient (there are 177B HOT issued already, so the Holo
/// infrastructure account will be in a debit condition beyond this value).
///
/// With 6 decimal digits of fractional precision (a minimum transaction of 1/1,000,000 of a
/// HoloFuel), the range is log( 2**53 / 10 ** 6, 10 ) == 9.9545 digits of Holo fuel; almost 10
/// digits of precision, with a max capacity of about 9,007,199,254 HoloFuel; still insufficient to
/// represent the debit balance of the Holo organization which issued the HOT.
///
/// Therefore, we allow the full range of i128 values for Fuel.units -- and disallow/discourage
/// calculation on Fuel values in Javascript code; unless you use Big values, you *will* (very, very
/// probably) do it wrong, and lose precision with large Fuel values.
///
/// By allowing the full i128 range for HoloFuel units (1/10^6 of a HoloFuel), we achieve a maximum
/// range of +/- of log( 2**63 / 10 ** 6 ) == 12.96 digits of HoloFuel capacity; about
/// 9,223,372,036,854 (9.223 Trillion) HoloFuel account and transaction value capacity; adequate for
/// any single HoloFuel account value or Transaction amount.  Any transaction the exceeds these
/// values will fail to complete (as all calculations are strictly bounds-checked).
///
/// The minimum fractional minimum amount of 1/10^6 HoloFuel allows for micro-transactions down to
/// 1/1,000,000th (1 millionth) of a HoloFuel.  Fee payments lose precision below value of
/// 1/10,000th of a HoloFuel; for example, if a micro-transaction of 0.000123 HoloFuel is spent, the
/// 1% fee that will be computed and charged could be 0.000001 HoloFuel if rounded down, or 0.000002
/// if rounded up.
///
/// Since the system "cost" of extremely tiny transactions is not free, fees on the portion of
/// transactions below the minimum threshold are always rounded up (away from 0).  This doesn't
/// affect the fee calculation of fees on transactions of precision 0.0001 or above (ie. the fee for
/// spending .0021 HoloFuel is exactly 0.000021).  However, the fee for spending 0.00213 is computed
/// as 0.000022 (is round up), instead of 0.000021 (normal rounding).  Perhaps surprisingly, the fee
/// to spend 0.000001 HoloFuel is 0.000001.  In effect, the fees on extremely tiny transactions
/// increase from 1%, up to 100% fees on the tiniest possible transaction.  This better reflects the
/// actual costs of running the Holo system, and is not an egregious cost; 1,000 such transactions
/// would cost an additional 0.001 HoloFuel in fees (vs. fees calculated with infinite precision).
///

// FRACTION -- units of Holo fuel are stored to this fixed-point precision.  These must
// be consistent with each-other.  Values after the decimal point are truncated to the
// EXPONENT number of significant decimal places; the remainder are ignored.
pub const EXPONENT: usize = 18; // Up to 18 digits after decimal (>6 truncated)
pub const DENOMINATOR: i64 = 1_000_000_000_000_000_000; // eg. 10 ^ EXPONENT

pub const INTLIMIT: usize = 18; // Up to 18 digits before decimal (~18.96 accepted)
pub const HEXLIMIT: usize = 36; // Up to 36 hex digits (full 128-bit signed twos-complement integer)

// These {MIN,MAX}{VALUE,RANGE} values are *carefully* chosen to avoid the possibility of
// over/underflow at the limits of u128/i128 interactions in Fuel calculations.  Do not consider
// changing without carefully considering/testing the effects at the limits of possible value.
pub const MAXVALUE: i128 = i128::max_value(); // 748288838313422294120286634350736906063837462003712;
pub const MAXRANGE: u128 = MAXVALUE as u128;

pub const MINVALUE: i128 = -MAXVALUE - 1; // == i128::min_value();
pub const MINRANGE: u128 = MAXRANGE + 1;

// DECSHOWN -- default number of decimal places desired after '.' in Display values
pub const DECSHOWN: usize = 1; // could be 1-EXPONENT

#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq)] // Copy req'd for binary op implementations
/// Holo Fuel, in 1/DENOMINATOR units
pub struct Fuel {
    pub units: i128,
}

/// fuel::FuelResult -- a fully defined custom Result type for Holo fuel operations
pub type FuelResult = result::Result<Fuel, FuelError>;

/// Serialize as human-readable string, eg. "1.02" instead of { units: 102000000 }
///
/// This format is unambiguous and retains all precision of the raw units value, and is
/// automatically serialized to/from a JSON string type.
impl Serialize for Fuel {
    fn serialize<S>(&self, serializer: S) -> result::Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.to_string().as_ref())
    }
}

impl<'d> Deserialize<'d> for Fuel {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'d>,
    {
        let s = String::deserialize(deserializer)?;
        Fuel::from_str(&s).map_err(|e| de::Error::custom(e.to_string()))
    }
}

impl Fuel {
    pub fn new(units: i128) -> Self {
        Fuel { units }
    }

    pub fn check(amount: &str) -> Result<bool, FuelError> {
        lazy_static! {
            // Either 'hex', or 'int' and optionally 'fra' will be set if RE matches.
            // Failure to construct this regex is a terminal failure; .unwrap() and
            // panic! is appropriate.
            static ref FUEL_RE: Regex = Regex::new( &format!( r"(?x)
                ^\s*
                (?P<sig>[-+]?)
                \s*
                (?:
                    (?:0x(?P<hex>[a-fA-F0-9]{{1,{hexlimit}}}))
                    |(?:[H♓]?\s*
                    (?:
                        (?P<int>\d{{1,{intlimit}}})\.?
                        |(?P<mnt>\d{{0,{intlimit}}})\.(?P<frc>\d+)
                    )
                    )
                )
                \s*$", hexlimit = HEXLIMIT, intlimit = INTLIMIT )).unwrap();
        }

        let caps = FUEL_RE
            .captures(amount)
            .ok_or_else(|| FuelError::Range(format!("Invalid Holo fuel amount {}", amount)))?;
        let sign = match caps.name("sig") {
            Some(cap) => cap.as_str(),
            None => "",
        };

        match sign {
            "-" => Err(FuelError::Range(format!(
                "Invalid negative amount {}",
                amount
            ))),
            _ => Ok(true),
        }
    }
}

/// u128_to_i128 -- range-checked, optionally negating mantissa + fraction for Fuel.units.  Ensures
/// that supplied range (and fuel MIN/MAX-VALUEs are not exceeded).  This is a subtle operation,
/// which requires us to pre-validate absolute (unsigned) mantissa and fractional fuel unit values
/// before any negative sign is applied.
pub fn u128_to_i128(
    negative: bool,
    mantissa: u128,
    fraction: u128,
    range: u128,
) -> Result<i128, FuelError> {
    match mantissa.checked_add(fraction) {
        Some(u_units) => {
            if u_units > range {
                Err(FuelError::Range(format!(
                    "Exceeded range for Holo fuel mantissa {}, fraction {}",
                    mantissa, fraction
                )))
            } else if negative {
                if u_units > MINRANGE {
                    Err(FuelError::Range(format!(
                        "Underflow for Holo fuel negative mantissa {}, fraction {}",
                        mantissa, fraction
                    )))
                } else if u_units == MINRANGE {
                    Ok(MINVALUE)
                } else {
                    Ok(-(u_units as i128))
                }
            } else {
                Ok(u_units as i128)
            }
        }
        None => Err(FuelError::Range(format!(
            "Overflow for Holo fuel mantissa {}, fraction {}",
            mantissa, fraction
        ))),
    }
}

/// Fuel::from_str -- Covert from &str; Result may yield Err if parsing fails
///
/// Handles hexadecimal and normal whole or fractional amounts of Holo fuel, discarding any
/// precision beyond the 8th (EXPONENT) decimal place of fractional precision.  Returns FuelError
/// on any parsing or result value max range errors.
///
impl FromStr for Fuel {
    type Err = FuelError;

    fn from_str(amount: &str) -> result::Result<Self, Self::Err> {
        lazy_static! {
            // Either 'hex', or 'int' and optionally 'fra' will be set if RE matches.
            // Failure to construct this regex is a terminal failure; .unwrap() and
            // panic! is appropriate.
            static ref FUEL_RE: Regex = Regex::new( &format!( r"(?x)
                ^\s*
                (?P<sig>[-+]?)
                \s*
                (?:
                  (?:0x(?P<hex>[a-fA-F0-9]{{1,{hexlimit}}}))
                 |(?:[H♓]?\s*
                    (?:
                      (?P<int>\d{{1,{intlimit}}})\.?
                     |(?P<mnt>\d{{0,{intlimit}}})\.(?P<frc>\d+)
                    )
                  )
                )
                \s*$", hexlimit = HEXLIMIT, intlimit = INTLIMIT )).unwrap();
        }

        let caps = FUEL_RE
            .captures(amount)
            .ok_or_else(|| FuelError::Range(format!("Invalid Holo fuel amount {}", amount)))?;

        // RE matched.  Either a hex, and int or a mnt (mantissa, possibly empty) is required.  We
        // will parse the mantissa and fraction as an *unsigned* u128, because we must allow full
        // [0,MINVALUE] range in the mantissa, which is not representable in an i128.
        let mantissa = match caps.name("hex") {
            None => match caps.name("int") {
                None => match caps.name("mnt") {
                    // not hex or int; must be a mantissa (possibly empty, if just ".123")
                    None => {
                        return Err(FuelError::Range(
                            // No 'hex', 'int', or 'mnt' found? Failure of FUEL_RE
                            format!("Invalid Holo fuel amount {}", amount),
                        ));
                    }
                    Some(mnt) => match mnt.as_str().as_ref() {
                        "" => 0_u128,
                        mnt_str => {
                            DENOMINATOR as u128
                                * u128::from_str_radix(mnt_str, 10).or_else(|_| {
                                    Err(FuelError::Range(format!(
                                        "Invalid Holo fuel amount {}; bad mantissa {}",
                                        amount,
                                        mnt.as_str()
                                    )))
                                })?
                        }
                    },
                },
                Some(int) => {
                    DENOMINATOR as u128
                        * u128::from_str_radix(int.as_str(), 10).or_else(|_| {
                            Err(FuelError::Range(format!(
                                "Invalid Holo fuel amount {}; bad int {}",
                                amount,
                                int.as_str()
                            )))
                        })?
                }
            },
            Some(hex) => u128::from_str_radix(hex.as_str(), 16).or_else(|_| {
                Err(FuelError::Range(format!(
                    "Invalid Holo fuel amount {}; bad hex {}",
                    amount,
                    hex.as_str()
                )))
            })?,
        };
        // Allow up the full capacity of a u128 worth of fractional digits, then truncate/zero-extend
        // to EXPONENT width.
        let fraction: u128 = match caps.name("frc") {
            None => 0,
            Some(fra) => u128::from_str_radix(
                // ".5" ==> "50000000" (truncate/fill to exactly EXPONENT width)
                &format!(
                    "{:0<exponent$.exponent$}",
                    fra.as_str(),
                    exponent = EXPONENT
                ),
                10,
            )
            .or_else(|_| {
                Err(FuelError::Range(format!(
                    "Invalid Holo fuel amount {}; bad fraction {}",
                    amount,
                    fra.as_str()
                )))
            })?,
        };
        let sign = match caps.name("sig") {
            Some(cap) => cap.as_str(),
            None => "",
        };

        let units_res = match sign {
            "-" => u128_to_i128(true, mantissa, fraction, MINRANGE), // -...
            _ => u128_to_i128(false, mantissa, fraction, MAXRANGE),  // ..., or +...
        };
        let amount_fuel = match units_res {
            Ok(units) => Fuel { units },
            Err(e) => return Err(e),
        };

        //println!( "Holo fuel amount {} ==> sign \"{}\", mantissa {}, fraction {} == {}]",
        //          amount, sign, mantissa, fraction, amount_fuel );

        Ok(amount_fuel)
    }
}

/// i128 -> Fuel for all integer types
impl From<i128> for Fuel {
    fn from(units: i128) -> Fuel {
        Fuel { units }
    }
}

/// & mut Fuel -> Fuel required for in-place operators
impl From<&mut Fuel> for Fuel {
    fn from(other: &mut Fuel) -> Fuel {
        Fuel { units: other.units }
    }
}

///
/// Holo fuel amounts in human-readable Display representation
///
/// All integer numeric forms of Holo fuel are deemed to be terms if 1/DENOMINATOR units.  Floating
/// point amounts are not acceptable, due to loss of precision.
///
/// All String/&str forms are deemed to be in "whole.fractional" amounts, and are converted to
/// internal 1/DENOMINATOR units.
///
/// If no fractional units are used, then the Fuel amount is represented as a whole-numbered value;
/// at least 1 fractional digit of precision is displayed (more, if required to represent the value
/// without loss of precision.).
///
/// # Examples
/// ```
/// use holofuel_types::fuel::Fuel;
/// let f1 = Fuel::from( 1234567890 );
/// let d1 = format!( "{}", f1 );
/// ```
///
impl fmt::Display for Fuel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let sign = if self.units < 0 { "-" } else { "" };
        let whole = self.units / (DENOMINATOR as i128); //            1234098760 / 10^6 == 1234
        let fraction = self.units - whole * (DENOMINATOR as i128); // 1234098760 - 1234 * 10^6 == 98760
                                                                   // fraction must be < DENOMINATOR, and will be +'ve or -'ve (same sign as self.units)
        if fraction == 0 {
            write!(f, "{}{}", sign, whole.abs())
        } else {
            // Any fractional portion is left-padded with '0' out to 8 (EXPONENT) decimal points,
            // and then trimmed of terminal '0's.  Then, we provide at least DECSHOWN fractional
            // decimal places, 0-filled on the right.  This allows us to tune the default fractional
            // precision of Fuel, similarly to how dollars is typically shown with 2 decimals of
            // precision, eg. $1.20.                          98760 ==> 098760
            let decimals = format!("{:0>exponent$}", fraction.abs(), exponent = EXPONENT);
            let decimals = decimals.trim_end_matches('0'); // 098760 ==> 09876
            write!(
                f,
                "{}{}.{:0<decshown$}",
                sign,
                whole.abs(),
                decimals,
                decshown = DECSHOWN
            )
        }
    }
}

impl fmt::Debug for Fuel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "Fuel({})", self)
    }
}

///
/// Fuel Operators -- Numerical operations with/without validity check
///
/// Neg, Add, Sub, Mul, Div of Fuel always results in a checked Result<Fuel, FuelError> value.
/// So, it is necessary to handle the FuelError that may result from invalid computations
/// before assigning any valid Fuel result:
///
/// > let Fuel: value = ( Fuel::from_str( "1.0" ) + Fuel::from_str( "2.0" ) )?
///
/// Attempting to use an existing Result::Err always maintains the lhs-most Err.
///

/// Negation of Fuel can lead to an error at MINVALUE, so FuelResult is returned.  Because we cannot
/// implement Neg for non-local type result::Result<Fuel,...>, to negate an &FuelResult, use
/// something like: fuel_result.to_owned().and_then(|f| -f)
impl Neg for Fuel {
    // - Fuel
    type Output = FuelResult;
    fn neg(self) -> FuelResult {
        Ok(match self.units.checked_neg() {
            Some(units) => Fuel { units },
            None => {
                return Err(FuelError::Range(format!(
                    "Overflow in negation of Holo fuel amount {}",
                    self
                )))
            }
        })
    }
}

impl Neg for &Fuel {
    // - &Fuel
    type Output = FuelResult;
    fn neg(self) -> FuelResult {
        -*self
    }
}

impl Add for Fuel {
    // Fuel + Fuel
    type Output = FuelResult;
    fn add(self, rhs: Fuel) -> Self::Output {
        Ok(match self.units.checked_add(rhs.units) {
            Some(units) => Fuel { units },
            None => {
                return Err(FuelError::Range(format!(
                    "Overflow in addition of Holo fuel amount {} + {}",
                    self, rhs
                )))
            }
        })
    }
}

impl Add<&Fuel> for Fuel {
    // Fuel + &Fuel
    type Output = FuelResult;
    fn add(self, rhs: &Fuel) -> Self::Output {
        self + *rhs
    }
}

impl Add<Fuel> for &Fuel {
    // &Fuel + Fuel
    type Output = FuelResult;
    fn add(self, rhs: Fuel) -> Self::Output {
        *self + rhs
    }
}

impl Add for &Fuel {
    // &Fuel + &Fuel
    type Output = FuelResult;
    fn add(self, rhs: &Fuel) -> Self::Output {
        *self + *rhs
    }
}

impl Add<FuelResult> for Fuel {
    // Fuel + Result<Fuel, FuelError>
    type Output = FuelResult;
    fn add(self, other: Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => self + rhs,
            Err(rhs_e) => Err(rhs_e),
        }
    }
}

impl Add<FuelResult> for &Fuel {
    // &Fuel + Result<Fuel, FuelError>
    type Output = FuelResult;
    fn add(self, other: Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => *self + rhs,
            Err(rhs_e) => Err(rhs_e),
        }
    }
}

impl Add<&FuelResult> for Fuel {
    // Fuel + &Result<Fuel, FuelError>
    type Output = FuelResult;
    fn add(self, other: &Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => self + *rhs,
            Err(rhs_e) => Err(rhs_e.clone()),
        }
    }
}

impl Add<&FuelResult> for &Fuel {
    // &Fuel + &Result<Fuel, FuelError>
    type Output = FuelResult;
    fn add(self, other: &Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => *self + *rhs,
            Err(rhs_e) => Err(rhs_e.clone()),
        }
    }
}

impl Add<Fuel> for FuelResult {
    // Result<Fuel, FuelError> + Fuel
    type Output = FuelResult;
    fn add(self, rhs: Fuel) -> Self::Output {
        match self {
            Ok(lhs) => lhs + rhs,
            Err(lhs_e) => Err(lhs_e),
        }
    }
}

impl Add<&Fuel> for FuelResult {
    // Result<Fuel, FuelError> + &Fuel
    type Output = FuelResult;
    fn add(self, rhs: &Fuel) -> Self::Output {
        match self {
            Ok(lhs) => lhs + *rhs,
            Err(lhs_e) => Err(lhs_e),
        }
    }
}

impl Add<Fuel> for &FuelResult {
    // &Result<Fuel, FuelError> + Fuel
    type Output = FuelResult;
    fn add(self, rhs: Fuel) -> Self::Output {
        match self {
            Ok(lhs) => *lhs + rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        }
    }
}

impl Add<&Fuel> for &FuelResult {
    // &Result<Fuel, FuelError> + &Fuel
    type Output = FuelResult;
    fn add(self, rhs: &Fuel) -> Self::Output {
        match self {
            Ok(lhs) => *lhs + *rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        }
    }
}

impl AddAssign<Fuel> for FuelResult {
    // Result<Fuel, FuelError> += Fuel
    fn add_assign(&mut self, rhs: Fuel) {
        *self = match self {
            Ok(lhs) => Fuel::from(lhs) + rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        };
    }
}

impl AddAssign<&Fuel> for FuelResult {
    // Result<Fuel, FuelError> += &Fuel
    fn add_assign(&mut self, rhs: &Fuel) {
        *self = match self {
            Ok(lhs) => Fuel::from(lhs) + rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        };
    }
}

impl Sub for Fuel {
    // Fuel - Fuel
    type Output = FuelResult;
    fn sub(self, rhs: Fuel) -> Self::Output {
        Ok(match self.units.checked_sub(rhs.units) {
            Some(units) => Fuel { units },
            None => {
                return Err(FuelError::Range(format!(
                    "Overflow in subtraction of Holo fuel amount {} - {}",
                    self, rhs
                )))
            }
        })
    }
}

impl Sub<&Fuel> for Fuel {
    // Fuel - &Fuel
    type Output = FuelResult;
    fn sub(self, rhs: &Fuel) -> Self::Output {
        self - *rhs
    }
}

impl Sub<Fuel> for &Fuel {
    // &Fuel - Fuel
    type Output = FuelResult;
    fn sub(self, rhs: Fuel) -> Self::Output {
        *self - rhs
    }
}

impl Sub for &Fuel {
    // &Fuel - &Fuel
    type Output = FuelResult;
    fn sub(self, rhs: &Fuel) -> Self::Output {
        *self - *rhs
    }
}

impl Sub<FuelResult> for Fuel {
    // Fuel - Result<Fuel, FuelError>
    type Output = FuelResult;
    fn sub(self, other: Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => self - rhs,
            Err(rhs_e) => Err(rhs_e),
        }
    }
}

impl Sub<FuelResult> for &Fuel {
    // &Fuel - Result<Fuel, FuelError>
    type Output = FuelResult;
    fn sub(self, other: Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => *self - rhs,
            Err(rhs_e) => Err(rhs_e),
        }
    }
}

impl Sub<&FuelResult> for Fuel {
    // Fuel - &Result<Fuel, FuelError>
    type Output = FuelResult;
    fn sub(self, other: &Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => self - *rhs,
            Err(rhs_e) => Err(rhs_e.clone()),
        }
    }
}

impl Sub<&FuelResult> for &Fuel {
    // &Fuel - &Result<Fuel, FuelError>
    type Output = FuelResult;
    fn sub(self, other: &Self::Output) -> Self::Output {
        match other {
            Ok(rhs) => *self - *rhs,
            Err(rhs_e) => Err(rhs_e.clone()),
        }
    }
}

impl Sub<Fuel> for FuelResult {
    // Result<Fuel, FuelError> - Fuel
    type Output = FuelResult;
    fn sub(self, rhs: Fuel) -> Self::Output {
        match self {
            Ok(lhs) => lhs - rhs,
            Err(lhs_e) => Err(lhs_e),
        }
    }
}

impl Sub<&Fuel> for FuelResult {
    // Result<Fuel, FuelError> - &Fuel
    type Output = FuelResult;
    fn sub(self, rhs: &Fuel) -> Self::Output {
        match self {
            Ok(lhs) => lhs - *rhs,
            Err(lhs_e) => Err(lhs_e),
        }
    }
}

impl Sub<Fuel> for &FuelResult {
    // &Result<Fuel, FuelError> - Fuel
    type Output = FuelResult;
    fn sub(self, rhs: Fuel) -> Self::Output {
        match self {
            Ok(lhs) => *lhs - rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        }
    }
}

impl Sub<&Fuel> for &FuelResult {
    // &Result<Fuel, FuelError> - &Fuel
    type Output = FuelResult;
    fn sub(self, rhs: &Fuel) -> Self::Output {
        match self {
            Ok(lhs) => *lhs - *rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        }
    }
}

impl SubAssign<Fuel> for FuelResult {
    // Result<Fuel, FuelError> -= Fuel
    fn sub_assign(&mut self, rhs: Fuel) {
        *self = match self {
            Ok(lhs) => Fuel::from(lhs) - rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        };
    }
}

impl SubAssign<&Fuel> for FuelResult {
    // Result<Fuel, FuelError> -= &Fuel
    fn sub_assign(&mut self, rhs: &Fuel) {
        *self = match self {
            Ok(lhs) => Fuel::from(lhs) - rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        };
    }
}

/// Fuel * Fraction, Fuel / Fraction -- always round up on loss of precision
///
/// If a Fraction's numerator would result in an overflow of the maximum allowable Holo fuel amount,
/// produce an Err result.  Non-zero results below the minimum fractional Fuel value threshold are
/// always rounded up.
///
/// For example, .75% of 1334 == 10.005, or 11 if rounded up.  A Fraction representing .75%,
/// `Fraction::new(3, 400)` multiplied by 0.001334 HoloFuel: `Fuel{ units: 1334 }` would result in a
/// `Some(quotient)` of 1334 / 400 == 3, and then 3 * 3 == 9.
///
/// In general, any HoloFuel.units precision below the Fraction.denominator will be lost, because we
/// perform a division by the Fraction.denominator, to avoid overflow on large values.  If we had
/// instead performed the multiplication by the numerator first, we would have have computed 1334 *
/// 3 == 4002, and 4002 / 400 == 10; also correct, but no more useful if our intent is to "round up"
/// since the desired result is 11 (and, it would overflow on large values).  However, here we could
/// clearly detect that 4002 % 400 == 2 remainder, indicating that we must add 1 to the result to
/// round up.
///
/// We must find the remainder of the division by the denominator 400, after multiplying it by the
/// numerator, see if (when rounded up by just less than the denominator), how many multiples of the
/// denominator we missed:
///
/// //          1334 % 400 == 134,
/// //             134 * 3 == 402
/// //     402 + (400 - 1) == 801
/// //           801 / 400 == 2.
/// //
/// Since all of these are small numbers, overflow is not possible (unless the Fraction is huge)
///
/// Note the checked_rem is a signed remainder, not a euclidean modulo, eg. from
/// https://internals.rust-lang.org/t/mathematical-modulo-operator/5952:
///
/// // Remainder operator (%)
/// //   5 %  3 //  2
/// //   5 % -3 //  2
/// //  -5 %  3 // -2
/// //  -5 % -3 // -2
///
/// // Modulo operator (%%)
/// //   5 %%  3 //  2
/// //   5 %% -3 // -1
/// //  -5 %%  3 //  1
/// //  -5 %% -3 // -2
///
/// Therefore, when multiplying by -'ve Fuel, any checked_rem will be remain -'ve
///
impl Mul<Fraction> for Fuel {
    // Fuel * Fraction
    type Output = FuelResult;
    fn mul(self, rhs: Fraction) -> Self::Output {
        match self.units.checked_div(rhs.denominator) {
            Some(quotient) => match quotient.checked_mul(rhs.numerator) {
                Some(units) => match self
                    .units
                    .checked_rem(rhs.denominator)
                    .and_then(|e| e.checked_mul(rhs.numerator))
                    .and_then(|e| {
                        if e >= 0 {
                            e.checked_add(rhs.denominator - 1)
                        } else {
                            e.checked_sub(rhs.denominator - 1)
                        }
                    })
                    .and_then(|e| e.checked_div(rhs.denominator))
                {
                    Some(extra) => Ok(Fuel {
                        units: units + extra,
                    }),
                    None => Err(FuelError::FractionOverflow((self, rhs))),
                },
                None => Err(FuelError::FractionOverflow((self, rhs))),
            },
            None => Err(FuelError::FractionOverflow((self, rhs))),
        }
    }
}

impl Mul<&Fraction> for Fuel {
    // Fuel * &Fraction
    type Output = FuelResult;
    fn mul(self, rhs: &Fraction) -> Self::Output {
        self * *rhs
    }
}

impl Mul<Fraction> for &Fuel {
    // &Fuel * Fraction
    type Output = FuelResult;
    fn mul(self, rhs: Fraction) -> Self::Output {
        *self * rhs
    }
}

impl Mul<&Fraction> for &Fuel {
    // &Fuel * &Fraction
    type Output = FuelResult;
    fn mul(self, rhs: &Fraction) -> Self::Output {
        *self * *rhs
    }
}

impl MulAssign<Fraction> for FuelResult {
    // Result<Fuel, FuelError> *= Fraction
    fn mul_assign(&mut self, rhs: Fraction) {
        *self = match self {
            Ok(lhs) => Fuel::from(lhs) * rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        };
    }
}

impl MulAssign<&Fraction> for FuelResult {
    // Result<Fuel, FuelError> *= &Fraction
    fn mul_assign(&mut self, rhs: &Fraction) {
        *self = match self {
            Ok(lhs) => Fuel::from(lhs) * rhs,
            Err(lhs_e) => Err(lhs_e.clone()),
        };
    }
}

impl Div<Fraction> for Fuel {
    // Fuel / Fraction
    type Output = FuelResult;
    fn div(self, rhs: Fraction) -> Self::Output {
        self * Fraction {
            numerator: rhs.denominator,
            denominator: rhs.numerator,
        }
    }
}

impl Div<&Fraction> for Fuel {
    // Fuel / &Fraction
    type Output = FuelResult;
    fn div(self, rhs: &Fraction) -> Self::Output {
        self / *rhs
    }
}

impl Div<Fraction> for &Fuel {
    // &Fuel / Fraction
    type Output = FuelResult;
    fn div(self, rhs: Fraction) -> Self::Output {
        *self / rhs
    }
}

impl Div<&Fraction> for &Fuel {
    // &Fuel / &Fraction
    type Output = FuelResult;
    fn div(self, rhs: &Fraction) -> Self::Output {
        *self / *rhs
    }
}

/// Delta -- a Fuel value associated with a timestamp
#[derive(Deserialize, Debug, Serialize, Clone, PartialEq, Eq)]
pub struct Delta(pub Timestamp, pub Fuel);

/// Limit -- Computes and enforces a rolling Period's value.
///
/// We'll be using this for configuring amount/period limits, but will not allow incoming
/// configuration (deserializing) of recent Deltas -- only supports reporting (serializing) of the
/// most recent Deltas for each counterparty.
#[derive(Deserialize, Debug, Serialize, Clone, PartialEq, Eq)]
pub struct Limit {
    pub amount: Option<Fuel>,   // Some("1000.0") --> limit, None --> not allowed
    pub period: Option<Period>, // Some("1w") --> over time period, None --> each transaction
    #[serde(skip_deserializing, skip_serializing_if = "VecDeque::is_empty")]
    pub recent: VecDeque<Delta>, // Rolling history over period (not included in incoming API calls)
}

impl fmt::Display for Limit {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.period {
            None => match &self.amount {
                None // No Fuel amount or Period limit! Transactions with this agent are explicitly *denied*.
                    => write!(f, "(agent denied)"),
                Some(amount) // Fuel amount, but no Period specified.  Limit is applied on each Delta's change.
                    => write!(f, "{} / tx", amount),
            },
            Some(period) => match &self.amount {
                None // Period, but no Fuel amount.  Only a single transaction per Period is allowed.
                    => write!(f, "1 tx / {}", period),
                Some(amount) // Both Period and Fuel; a maximum Fuel amount for the Period has been specified.
                    => write!(f, "{} / {}", amount, period),
            },
        }
    }
}

impl Limit {
    /// Tests to see if *any* transactions are allowed with this counterparty by this (incoming or outgoing) Limit
    pub fn allow(self: &Self) -> Result<(), FuelError> {
        if self.period.is_none() && self.amount.is_none() {
            Err(FuelError::AgentDenied(self.to_owned()))
        } else {
            Ok(())
        }
    }
    /*
    /// delta -- Computes the current value of this Fuel amount change, effective at timestamp
    ///
    /// Updates self.recent w/ latest Delta's relevant to the .period (hence, needs self: &mut Self)
    ///
    /// For a non-Periodic Limit, this just validates the amount.  For Period-based Limits, a vector
    /// of the last Period's worth of balance changes are kept, and the sum is computed.  If the
    /// supplied value is invalid (exceeds the Limit), or is wildly out of order (ie. older than the
    /// oldest entry already in the `recent` heap), or overflows, or is otherwise suspect, a
    /// FuelError will result, indicating failure of the proposed change.  On success, the original
    /// Fuel value is returned as a FuelResult.  If the fuel `change` is already in Err FuelResult,
    /// it will be passed through (retaining the Err).
    ///
    /// WARNING: This must be invoked carefully (eg. only once, with each new Delta(timestamp,
    /// change)), or the same "transaction" could easily result in failure.  We know that,
    /// presently, it is invoked during operation of the state machine, which prevents the commit of
    /// duplicate Events.  However, if other validation code is written that accidentally invokes
    /// this more than once (eg. checks first in the state machine, and again later, somewhere
    /// else), we could get erroneous results.  If we *test* for idempotency, here, though -- we
    /// could erroneously detect two sequential, valid, transactions with *identical* amounts, that
    /// happened to be processed in (what appears to be) the same instant of time.  Even if the
    /// system clock is guaranteed to be monotonic and increasing (which they are often *not*), we
    /// can't guarantee that two subsequent Events will have unique timestamps.  So, we do *not*
    /// check for idempotency.
    //TODO: impl Timestamp + Period
    pub fn delta(self: &mut Self, timestamp: &Timestamp, change: &FuelResult) -> FuelResult {
        // Filter out already `change` that are already Err.
        let change_fuel = match change {
            Err(_e) => return change.to_owned(),
            Ok(f) => f.to_owned(),
        };
        let change_delta = Delta(timestamp.to_owned(), change_fuel);
        match &self.period {
            None => {
                match self.amount {
                    Some(amount) => {
                        // Fuel amount, but no Period specified.  Limit is applied on each Delta's change.
                        if change_fuel > amount {
                            return Err(FuelError::LimitExceeded((
                                self.to_owned(),
                                amount.to_string(),
                                change_delta,
                            )));
                        }
                    }
                    None => {
                        // No Fuel amount or Period limit! Transactions with this agent are
                        // explicitly *denied*.  For example, if the "default" limits are tight, but
                        // exceptions are specified for certain known accounts, or if certain
                        // counterparties are explicitly disallowed from incoming/outgoing
                        // transactions.  To specify *no* limit, provide empty vector() in
                        // TxLimits.incoming/outgoing (ie. Here's the limits for .incoming -- and
                        // there aren't any).
                        return Err(FuelError::AgentDenied(self.to_owned()));
                    }
                }
            }
            Some(period) => {
                // Compute the oldest allowed entry in .recents, by offset from timestamp; the any
                // Deltas >= oldest computed will be purged.  The oldest are at the front of
                // .recents.

                // let oldest = (timestamp.clone() + period)?;
                // Discard .recent Deltas greater or *equal*, so that Deltas that arrive at
                // *exactly* the rate Period don't exceed the Limit.
                while let Some(d) = self.recent.front() {
                    // self.recent.get(0) {
                    if d.0 >= oldest {
                        self.recent.pop_front(); // self.recent.drain(..1).for_each(drop);
                    } else {
                        break;
                    }
                }

                self.recent.push_back(change_delta.clone()); // self.recent.push(change_delta.clone());
                match self.amount {
                    Some(fuel) => {
                        // Both Period and Fuel; a maximum Fuel amount for the Period has been
                        // specified.  Ensure we haven't exceeded it.  Sum up all the recent deltas
                        // and ensure we detect overflow, using FuelResult + Fuel
                        let sum = self
                            .recent
                            .iter()
                            .fold(FuelResult::from(Ok(Fuel::from(0))), |acc, d| acc + d.1)?;
                        if sum > fuel {
                            return Err(FuelError::LimitExceeded((
                                self.to_owned(),
                                sum.to_string(),
                                change_delta,
                            )));
                        }
                    }
                    None => {
                        // Period, but no Fuel amount.  Only a single transaction per Period is allowed.
                        println!(
                            "Limit {} appends recent: {:?} len {}",
                            self,
                            &change_delta,
                            self.recent.len()
                        );
                        if self.recent.len() > 1 {
                            return Err(FuelError::LimitExceeded((
                                self.to_owned(),
                                Fuel::from(0).to_string(),
                                change_delta,
                            )));
                        }
                    }
                }
            }
        }

        change.to_owned() // On success, returns the original Fuel amount
    }
    */
}

#[cfg(test)]
pub mod tests {
    use crate::fuel::{self, u128_to_i128, Fuel, FuelResult};
    use std::str::FromStr;

    #[test]
    /// smoke test Fuel
    fn fuel_smoke_test() {
        let f1 = Fuel::from_str("1.0").unwrap();
        //let f1 = Fuel::from_str( "0x5f5e100" ).unwrap();
        assert_eq!(f1.units, 1 * fuel::DENOMINATOR as i128);
        // Whole numbered values do not include fractional precision
        let d1 = format!("{}", f1);
        assert_eq!(
            d1,
            match fuel::DECSHOWN {
                1 => "1",
                2 => "1",
                3 => "1",
                4 => "1",
                5 => "1",
                6 => "1",
                7 => "1",
                8 => "1",
                _ => "unknown",
            }
        );

        let f2 = Fuel::from(-1234567890987654321);
        assert_eq!(f2.units, -1234567890987654321_i128);
        // At least the required amount of precision is always supplied to ensure no loss of data
        let d2 = format!("{}", f2);
        assert_eq!(
            d2,
            match fuel::DECSHOWN {
                6 => "-1234.567890",
                _ => "-1.234567890987654321",
            }
        );

        // Extending out fractions to fill at leas
        let f3 = Fuel::from_str("999.5").unwrap();
        assert_eq!(f3.units, 999_500_000_000_000_000_000_i128);

        let d3 = format!("{}", f3);
        assert_eq!(
            d3,
            match fuel::DECSHOWN {
                1 => "999.5",
                2 => "999.50",
                3 => "999.500",
                4 => "999.5000",
                5 => "999.50000",
                6 => "999.500000",
                7 => "999.5000000",
                8 => "999.50000000",
                _ => "unknown",
            }
        );

        // Ensure that excessive fractional amounts are truncated silently
        let f4 = Fuel::from_str("-1234.5678901234567890123456").unwrap();
        assert_eq!(f4.units, -1234567890123456789012);
        let d4 = format!("{}", f4);
        assert_eq!(d4, "-1234.567890123456789012");

        // See if precision retaining maximums are enforced.  We're assuming i128 is NOT actually
        // implemented as IEEE 754 double-precision (where +/- 2^53-1 is the precision-loss limit).
        // Try to round-trip full-precision Holo fuel values through Display "#.##"
        assert_eq!(
            fuel::MAXVALUE,
            170_141_183_460_469_231_731_687_303_715_884_105_727
        );
        assert_eq!(
            fuel::MAXRANGE,
            170_141_183_460_469_231_731_687_303_715_884_105_727
        );
        assert_eq!(
            fuel::MINVALUE,
            -170_141_183_460_469_231_731_687_303_715_884_105_728
        );
        assert_eq!(
            fuel::MINRANGE,
            170_141_183_460_469_231_731_687_303_715_884_105_728
        );

        assert_eq!(
            format!(
                "{:?}",
                Fuel::from_str(&"-1701411834604692.31731687303715884105728")
            ),
            "Ok(Fuel(-1701411834604692.317316873037158841))"
        );
        assert_eq!(
            format!(
                "{:?}",
                Fuel::from_str(&"-1701411834604692.31731687303715884105728")
            ),
            "Ok(Fuel(-1701411834604692.317316873037158841))"
        );
        match Fuel::from_str( &"0x80000000000000000000000000000000" ) { // MAXRANGE + 1
            Ok(f) => panic!( "Expected failure due to fuel::MAXRANGE did not occur: ♓{}", f ),
            Err(e) => assert_eq!( format!("{}", e ),
                                  "HoloFuel Range Error: Exceeded range for Holo fuel mantissa 170141183460469231731687303715884105728, fraction 0" ),
        }
        // Max Values that it will accept
        assert_eq!(
            format!("{:?}", Fuel::from_str(&"9999999999999999.9999999999999999")),
            "Ok(Fuel(9999999999999999.9999999999999999))"
        );
        assert_eq!(
            format!(
                "{:?}",
                Fuel::from_str(&"-9999999999999999.9999999999999999")
            ),
            "Ok(Fuel(-9999999999999999.9999999999999999))"
        );
        match Fuel::from_str(&"1_000_000_000_000_000_000") {
            Ok(f) => panic!(
                "Expected failure due to fuel::MINVRANGE did not occur: ♓{}",
                f
            ),
            Err(e) => assert_eq!(
                format!("{}", e),
                "HoloFuel Range Error: Invalid Holo fuel amount 1_000_000_000_000_000_000"
            ),
        }
    }

    #[test]
    fn fuel_operators() {
        // Fuel + Fuel
        let sum = Fuel::from_str("1.23").unwrap() + Fuel::from_str("-1000").unwrap();
        match &sum {
            Ok(ref f) => assert_eq!(format!("{}", f), "-998.77"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        // Result<Fuel,...> + Fuel
        let sum2 = sum + Fuel::from_str("100").unwrap();
        match &sum2 {
            Ok(ref f) => assert_eq!(format!("{}", f), "-898.77"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        // Fuel + Result<Fuel,...>
        let sum3 = Fuel::from_str("-1111.23").unwrap() + sum2;
        match &sum3 {
            Ok(ref f) => assert_eq!(format!("{}", f), "-2010"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Fuel + Fuel ref variants
        match Fuel::from(1_000_000_000_000_000_000) + Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match Fuel::from(1_000_000_000_000_000_000) + &Fuel::from(2) {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000002"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(2_000_000_000_000_000_000) + Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "2.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(2_000_000_000_000_000_000) + &Fuel::from(2) {
            Ok(f) => assert_eq!(format!("{}", f), "2.000000000000000002"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Result<Fuel,...> + Fuel ref variants
        match Fuel::from_str("1") + Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match Fuel::from_str("1") + &Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from_str("1") + Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from_str("1") + &Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Fuel + Result<Fuel,...> ref variants
        match Fuel::from(1) + Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(1) + Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match Fuel::from(1) + &Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(1) + &Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Result<Fuel,...> += Fuel ref variants
        let mut fa = Fuel::from_str("1");
        fa += Fuel::from(1);
        match fa {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        fa += &Fuel::from(-2);
        match fa {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Fuel - Fuel ref variants: 1.0 - 0.0000000000000001
        match Fuel::from(1_000_000_000_000_000_000) - Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match Fuel::from(1_000_000_000_000_000_000) - &Fuel::from(2) {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999998"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(2_000_000_000_000_000_000) - Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "1.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(2_000_000_000_000_000_000) - &Fuel::from(2) {
            Ok(f) => assert_eq!(format!("{}", f), "1.999999999999999998"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Result<Fuel,...> - Fuel ref variants: 1.0 - 0.0000000000000001
        match Fuel::from_str("1") - Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match Fuel::from_str("1") - &Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from_str("1") - Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from_str("1") - &Fuel::from(1) {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Fuel - Result<Fuel,...> ref variants: 0.000001 - 1.0
        match Fuel::from(1) - Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "-0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(1) - Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "-0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match Fuel::from(1) - &Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "-0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        match &Fuel::from(1) - &Fuel::from_str("1") {
            Ok(f) => assert_eq!(format!("{}", f), "-0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // Check all Result<Fuel,...> -= Fuel ref variants
        let mut fa = Fuel::from_str("1");
        fa -= Fuel::from(1);
        match fa {
            Ok(f) => assert_eq!(format!("{}", f), "0.999999999999999999"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        fa -= &Fuel::from(2_000_000_000_000_000_001);
        match fa {
            Ok(f) => assert_eq!(format!("{}", f), "-1.000000000000000002"),
            Err(e) => panic!("Expected success, not {}", e),
        }
        fa -= &Fuel::from(-2_000_000_000_000_000_003);
        match fa {
            Ok(f) => assert_eq!(format!("{}", f), "1.000000000000000001"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // And make sure errors produced and propogate; later terms just propogate original Err(_)
        match Fuel::from( u128_to_i128( true, fuel::MINRANGE, 0_u128, fuel::MINRANGE ).unwrap() ) - Fuel::from( 1 )  {
            Ok(f) => panic!( "Expected failure, not {}", f ),
            Err(e) => assert_eq!( format!( "{}", e ),
                                  "HoloFuel Range Error: Overflow in subtraction of Holo fuel amount -170141183460469231731.687303715884105728 - 0.000000000000000001" ),
        }
        match Fuel::from( u128_to_i128( true, fuel::MINRANGE, 0_u128, fuel::MINRANGE ).unwrap() ) - Fuel::from( 1 ) + Fuel::from( 1 ) {
            Ok(f) => panic!( "Expected failure, not {}", f ),
            Err(e) => assert_eq!( format!( "{}", e ),
                                  "HoloFuel Range Error: Overflow in subtraction of Holo fuel amount -170141183460469231731.687303715884105728 - 0.000000000000000001" ),
        }

        // Try negation
        assert_eq!(
            format!("{}", (-Fuel::from(fuel::MAXVALUE)).unwrap()),
            "-170141183460469231731.687303715884105727"
        );
        assert_eq!(
            format!("{}", (-&Fuel::from(fuel::MAXVALUE)).unwrap()),
            "-170141183460469231731.687303715884105727"
        );
        // Negating the largest negative value should lead to overflow
        assert_eq!(
            format!("{:?}", -&Fuel::from(fuel::MINVALUE)),
            "Err(Range(\"Overflow in negation of Holo fuel amount -170141183460469231731.687303715884105728\"))"
        );
    }

    #[test]
    fn fuel_comparisons() {
        assert_eq!(Fuel::from(1_000_001) > Fuel::from(1_000_000), true);
        assert_eq!(Fuel::from(1_000_001) < Fuel::from(1_000_000), false);
        assert_eq!(Fuel::from(1_000_000) < Fuel::from(1_000_001), true);

        assert_eq!(Fuel::from(1_000_000) == Fuel::from(1_000_001), false);
        assert_eq!(Fuel::from(1_000_000) <= Fuel::from(1_000_001), true);
        assert_eq!(Fuel::from(1_000_000) >= Fuel::from(1_000_001), false);

        assert_eq!(Fuel::from(1_000_000) == Fuel::from(1_000_000), true);
        assert_eq!(Fuel::from(1_000_000) <= Fuel::from(1_000_000), true);
        assert_eq!(Fuel::from(1_000_000) >= Fuel::from(1_000_000), true);
    }

    use crate::fraction::Fraction;
    #[test]
    fn fuel_compute_fees() {
        // Transaction fee computation requires computing a percentage, which is typically something like:
        //
        //     amount * ( 100 / <percentage> )
        //
        // where <percentage> is something like 1, 4, 0.25
        //
        // However, we don't want to perform floating point operations, nor prevent the calculation
        // of TX fees on values up to the maximum value, so we can't multiply amounts by numbers
        // before dividing.
        //
        // So, transaction fees have to be computable using division and addition/subtraction only.
        //
        // .25% is 1/400th, 3.5% is 35/1000 is 7/200ths.  So, we'll support multiplying by a ratio,
        // where we will first divide by the denominator before multiplying by the numerator. This
        // can lose precision on small values; for example, taking 3.5% of a value below 200 Holo
        // Fuel::units will result in fees of 0, instead of 7: 199 / 200 * 7 == 0.  And even on
        // larger values, since we're doing integer division, we'll still lose precision: 399 / 200
        // * 7 == 7, not the perhaps expected 13.  So, in essence, we'll always be "rounding down"
        // Holo fuel fees.  But, considering that Holo fuel is denominated in units of
        // 1/100,000,000th of a Holo Fuel, these rounding truncation errors will only be significant
        // when computing fees on exceedingly tiny transactions.

        let feepct = Fraction::new(35, 1000).reduce();
        assert_eq!((feepct.numerator, feepct.denominator), (7, 200));

        // Observe that we end up losing precision on very small transactions, and always round up.
        //
        // The infinite precision fee calculation should "round up" to H0.000014:
        //     H0.000399 * 7 / 200 == H0.000013965
        // But instead, we lose precision both by the reverse-ordering of multiplying out the
        // Fraction (to avoid overflow on large Fuel values), and through truncation:
        //     H0.000399     / 200 == H0.000001995 =~= H0.000001 * 7 == H0.000007
        // When we round up, we first compute the remainder of the division:
        //     H.000399      % 200 == 199
        // Then we amplify by the numerator and gross it up by 1 less than the denominator:
        //           199 * 7 + 199 == 1592
        // And then see how many denominators worth of rounding error we discarded:
        //              1592 / 200 == 7
        let feeamt = Fuel { units: 399 } * &feepct;
        match &feeamt {
            Ok(ref f) => assert_eq!(format!("{}", f), "0.000000000000000014"), // was "0.000007" w/o round up
            Err(e) => panic!("Expected success, not {}", e),
        }

        // See that division by the inverse Fraction is identical
        let inv_feepct = Fraction {
            denominator: feepct.numerator,
            numerator: feepct.denominator,
        };
        let feeamt = Fuel { units: 399 } / &inv_feepct;
        match &feeamt {
            Ok(ref f) => assert_eq!(format!("{}", f), "0.000000000000000014"),
            Err(e) => panic!("Expected success, not {}", e),
        }

        // And, we can be assured of being able to compute fees on the maximum transaction value,
        // 2^63-1: 9,223,372,036,854,775,807 * 7 / 200 == 322818021289917153.245, so rounded up we
        // should get a fee of: 322818021289917154, or H5954941421116423110.609055630055943701
        let amount = Fuel {
            units: fuel::MAXVALUE,
        };
        let feeamt = amount * &feepct;
        match feeamt {
            Ok(f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"), // was "322818021289.917153" w/o round up
            Err(e) => panic!("Expected success, not {}", e),
        };
        match Fuel::new(fuel::MINVALUE) * &feepct {
            // try -'ve, to ensure round up works
            Ok(f) => assert_eq!(format!("{}", f), "-5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };

        // Test all {T,&T} {*,/} {U,&U} combinations
        match Fuel::from(fuel::MAXVALUE) * Fraction::new(35, 1000).reduce() {
            Ok(f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };
        match &Fuel::from(fuel::MAXVALUE) * Fraction::new(35, 1000).reduce() {
            Ok(f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };
        match Fuel::from(fuel::MAXVALUE) * &Fraction::new(35, 1000).reduce() {
            Ok(f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };
        match &Fuel::from(fuel::MAXVALUE) * &Fraction::new(35, 1000).reduce() {
            Ok(ref f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };

        match Fuel::from(fuel::MAXVALUE) / Fraction::new(1000, 35).reduce() {
            Ok(f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };
        match &Fuel::from(fuel::MAXVALUE) / Fraction::new(1000, 35).reduce() {
            Ok(f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };
        match Fuel::from(fuel::MAXVALUE) / &Fraction::new(1000, 35).reduce() {
            Ok(f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };
        match &Fuel::from(fuel::MAXVALUE) / &Fraction::new(1000, 35).reduce() {
            Ok(ref f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };

        // Try in-place multiply; only works with mut Result<Fuel,...>, because result could be erroneous
        let mut feeamt: FuelResult = Ok(Fuel::from(fuel::MAXVALUE));
        feeamt *= feepct;
        match &feeamt {
            Ok(ref f) => assert_eq!(format!("{}", f), "5954941421116423110.609055630055943701"),
            Err(e) => panic!("Expected success, not {}", e),
        };

        // Force Fuel * Fraction overflow
        assert_eq!(
            format!(
                "{}",
                (Fuel::new(100) * Fraction::new(fuel::MAXVALUE, 2)).unwrap_err()
            ),
            "HoloFuel overflow in ♓0.0000000000000001 * 170141183460469231731687303715884105727/2"
        );
    }
}