'How do I decode the hex from a specific part of a BSC transaction receipt, using web3 py?

I am writing a python script using web3 package.

The process explained:

  1. I have a transaction, which I read the transaction receipt for

    txn_receipt = w3.eth.getTransactionReceipt('0x8ddd5ab8f53df7365a2feb8ee249ca2d317edcdcb6f40faae728a3cb946b4eb1')

  2. Just for this example, I read a specific section of the log. This returns a hex.

    x = txn_receipt['logs'][4]['data']

PROBLEM: How do I decode this hex? If you go to BSC SCAN, you will see the decoded value I am expecting at block 453.

Expected value:

amount0In :
2369737542851785768252
amount1In :
0
amount0Out :
0
amount1Out :
82650726831815053455

See here: https://bscscan.com/tx/0x8ddd5ab8f53df7365a2feb8ee249ca2d317edcdcb6f40faae728a3cb946b4eb1#eventlog



Solution 1:[1]

Assuming you don't need the key names, you could do this with basic python (no need for web3 library).

The data field in BSC logs is a string of hex encoded values, which is just a base 16 representation of the decimal value. In your example:

0x00000000000000000000000000000000000000000000008076b6fbd0ebb5bd3c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000047b025e26b62ed08f

Just trim the beginning, split it up, and convert each string with python's int() function:

hexdata = '0x00000000000000000000000000000000000000000000008076b6fbd0ebb5bd3c000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000047b025e26b62ed08f'

# Trim '0x' from beginning of string
hexdataTrimed = hexdata[2:]

# Split trimmed string every 64 characters
n = 64
dataSplit = [hexdataTrimed[i:i+n] for i in range(0, len(hexdataTrimed), n)]

# Fill new list with converted decimal values
data = []
for val in range(len(dataSplit)):
    toDec = int(dataSplit[val], 16)
    data.append(toDec)

print(data) 
# returns [2369737542851785768252, 0, 0, 82650726831815053455]

Sources:

https://www.binaryhexconverter.com/hex-to-decimal-converter https://www.w3schools.com/python/ref_func_int.asp

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1