[Ethereum] How to decode input data from tx using python3

blockchaincalldataraw-transactiontokenstransactions

I am trying to decode input data from token sale transactions. This is one of the transactions I am trying to parse 0xf7b7196ca9eab6e4fb6e7bce81aeb25a4edf04330e57b3c15bece9d260577e2b
Which has the following input data:
0xa9059cbb00000000000000000000000067fa2c06c9c6d4332f330e14a66bdf1873ef3d2b0000000000000000000000000000000000000000000000000de0b6b3a7640000

I know that the first 4 bytes represent the function (0xa9059cbb –> transfer)

The first parameter is the _to address (0x00000000000000000000000067fa2c06c9c6d4332f330e14a66bdf1873ef3d2b)

The second is _value who's type is uint256 (0x0000000000000000000000000000000000000000000000000de0b6b3a7640000).

How do I decode _value in python to get the amount of tokens being moved? I understand that for javascript there is abi-decoder which does something similar but I would like to know how to perform this myself in python.

I have read that the value is stored as a big endian int but when I try to read it, I do not get the value listed on etherscan for the transaction (https://etherscan.io/tx/0xf7b7196ca9eab6e4fb6e7bce81aeb25a4edf04330e57b3c15bece9d260577e2b)

The information I have about the parameter coding is from here: https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI

Best Answer

If you know the contract ABI, call data could be decoded using pyethereum:

from ethereum.abi import (
    decode_abi,
    normalize_name as normalize_abi_method_name,
    method_id as get_abi_method_id)
from ethereum.utils import encode_int, zpad, decode_hex

def decode_contract_call(contract_abi: list, call_data: str):
    call_data_bin = decode_hex(call_data)
    method_signature = call_data_bin[:4]
    for description in contract_abi:
        if description.get('type') != 'function':
            continue
        method_name = normalize_abi_method_name(description['name'])
        arg_types = [item['type'] for item in description['inputs']]
        method_id = get_abi_method_id(method_name, arg_types)
        if zpad(encode_int(method_id), 4) == method_signature:
            try:
                args = decode_abi(arg_types, call_data_bin[4:])
            except AssertionError:
                # Invalid args
                continue
            return method_name, args
Related Topic