Skip to content

Commit d1f6b67

Browse files
committed
updated method "to_hex()"
1 parent 6b4abaa commit d1f6b67

File tree

1 file changed

+34
-1
lines changed

1 file changed

+34
-1
lines changed

tronapi/tron.py

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
# SOFTWARE.
2222

2323
import binascii
24+
import json
25+
import numbers
2426
from _sha256 import sha256
2527
import base58
2628
import math
@@ -1073,7 +1075,7 @@ def to_utf8(hex_string):
10731075

10741076
@staticmethod
10751077
def from_utf8(string):
1076-
return binascii.hexlify(bytes(string, encoding="utf8")).decode()
1078+
return '0x' + binascii.hexlify(bytes(string, encoding="utf8")).decode()
10771079

10781080
@staticmethod
10791081
def from_decimal(value):
@@ -1113,6 +1115,37 @@ def from_sun(amount):
11131115
"""
11141116
return abs(amount) / 1e6
11151117

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+
11161149
@staticmethod
11171150
def sha3(string, prefix=False):
11181151
"""Helper function that will sha3 any value using keccak256

0 commit comments

Comments
 (0)