Line data Source code
1 : /*
2 : * Package : Ethereum
3 : * Author : S. Hamblett <steve.hamblett@linux.com>
4 : * Date : 06/011/2017
5 : * Copyright : S.Hamblett
6 : *
7 : * A JSON RPC 2.0 client for Ethereum
8 : */
9 :
10 : part of ethereum;
11 :
12 : /// General client support utilities
13 : class EthereumUtilities {
14 : /// Common pad values for intToHex
15 : static const int pad4 = 4;
16 : static const int pad8 = 8;
17 : static const int pad16 = 16;
18 : static const int pad32 = 32;
19 :
20 : /// Integer to hex string with leading 0x, lowercase.
21 : /// The optional pad value pads the string out to the number of bytes
22 : /// specified, i.e if 8 is specified the string 0x1 becomes 0x0000000000000001
23 : /// default is 0, no padding.The pad value must be even and positive.
24 : static String intToHex(int val, [int pad = 0]) {
25 2 : String ret = val.toRadixString(16);
26 2 : if (pad != 0) {
27 2 : if (pad.isNegative || pad.isOdd) {
28 1 : throw new FormatException(
29 1 : "EthereumUtilities:: intToHex - invalid pad value, $pad");
30 : }
31 2 : if (ret.length.isOdd) {
32 1 : ret = '0' + ret;
33 : }
34 3 : final int bytes = (ret.length / 2).round();
35 1 : if (bytes != pad) {
36 1 : final int zeroNum = (pad - bytes);
37 2 : for (int i = 0; i < zeroNum; i++) {
38 1 : ret = '00' + ret;
39 : }
40 : }
41 : }
42 2 : return '0x' + ret;
43 : }
44 :
45 : /// BigInteger to hex string
46 : static String bigIntegerToHex(BigInteger val) {
47 2 : return '0x' + val.toRadix(16);
48 : }
49 :
50 : /// Hex string to integer, a value of null indicates an error.
51 : /// The string must start with 0x
52 : static int hexToInt(String val) {
53 2 : return int.parse(val, onError: (val) => null);
54 : }
55 :
56 : /// Hex String list to Integer list
57 : static List<int> hexToIntList(List<String> val) {
58 1 : return new List<int>.generate(
59 3 : val.length, (int index) => hexToInt(val[index]));
60 : }
61 :
62 : /// Hex String list to BigInteger list
63 : static List<BigInteger> hexToBigIntegerList(List<String> val) {
64 2 : return new List<BigInteger>.generate(
65 6 : val.length, (int index) => new BigInteger(val[index]));
66 : }
67 :
68 : /// Integer list to Hex String list
69 : static List<String> intToHexList(List<int> val) {
70 1 : return new List<String>.generate(
71 3 : val.length, (int index) => intToHex(val[index]));
72 : }
73 :
74 : /// BigInteger list to Hex String list
75 : static List<String> bigIntegerToHexList(List<BigInteger> val) {
76 1 : return new List<String>.generate(
77 4 : val.length, (int index) => '0x' + val[index].toRadix(16));
78 : }
79 :
80 : /// Remove null values from a map
81 : static Map removeNull(Map theMap) {
82 2 : final List values = theMap.values.toList();
83 2 : final List keys = theMap.keys.toList();
84 : int index = 0;
85 2 : for (dynamic val in values) {
86 : if (val == null) {
87 2 : theMap.remove(keys[index]);
88 : }
89 1 : index++;
90 : }
91 : return theMap;
92 : }
93 : }
|