|
21 | 21 | # SOFTWARE. |
22 | 22 |
|
23 | 23 | import binascii |
| 24 | +import json |
| 25 | +import numbers |
24 | 26 | from _sha256 import sha256 |
25 | 27 | import base58 |
26 | 28 | import math |
@@ -1073,7 +1075,7 @@ def to_utf8(hex_string): |
1073 | 1075 |
|
1074 | 1076 | @staticmethod |
1075 | 1077 | def from_utf8(string): |
1076 | | - return binascii.hexlify(bytes(string, encoding="utf8")).decode() |
| 1078 | + return '0x' + binascii.hexlify(bytes(string, encoding="utf8")).decode() |
1077 | 1079 |
|
1078 | 1080 | @staticmethod |
1079 | 1081 | def from_decimal(value): |
@@ -1113,6 +1115,37 @@ def from_sun(amount): |
1113 | 1115 | """ |
1114 | 1116 | return abs(amount) / 1e6 |
1115 | 1117 |
|
| 1118 | + def to_hex(self, val): |
| 1119 | + """ |
| 1120 | + Helper function that will convert a generic value to hex. |
| 1121 | +
|
| 1122 | + Note: This function does not convert TRX addresses to Hex. |
| 1123 | + If you wish to specifically convert TRX addresses to HEX, |
| 1124 | + please use tron.address.to_hex instead. |
| 1125 | +
|
| 1126 | + Args: |
| 1127 | + val (str): Value to convert to hex. |
| 1128 | +
|
| 1129 | + Example: |
| 1130 | + >>> tron.to_hex("test") |
| 1131 | + >>> # result "74657374" |
| 1132 | +
|
| 1133 | + """ |
| 1134 | + if utils.is_bool(val): |
| 1135 | + return self.from_decimal(+val) |
| 1136 | + |
| 1137 | + if isinstance(val, (dict, object)): |
| 1138 | + return self.from_utf8(json.dumps(val).replace(' ', '')) |
| 1139 | + |
| 1140 | + if utils.is_string(val): |
| 1141 | + if val[:2] == '0x': |
| 1142 | + return val |
| 1143 | + |
| 1144 | + if not isinstance(val, numbers.Real): |
| 1145 | + return self.from_utf8(val) |
| 1146 | + |
| 1147 | + return self.from_decimal(val) |
| 1148 | + |
1116 | 1149 | @staticmethod |
1117 | 1150 | def sha3(string, prefix=False): |
1118 | 1151 | """Helper function that will sha3 any value using keccak256 |
|
0 commit comments