web3-input-decoder icon indicating copy to clipboard operation
web3-input-decoder copied to clipboard

Use HexBytes

Open ghost opened this issue 3 years ago • 4 comments

Hey @kigawas!

Nice idea to add a constructor decoder :) Might help to use HexBytes. Then you don't have to worry about detecting the constructor arguments and doing the processing as you can pass it to decode_abi. For example, something like this:

import json
import urllib.request
from eth_abi import decode_abi
from hexbytes import HexBytes

f = urllib.request.urlopen("https://api.etherscan.io/api?module=contract&action=getabi&address=0xdac17f958d2ee523a2206206994597c13d831ec7")
TETHER_ABI = json.loads(json.load(f)["result"])

def decode_constructor(args, abi):
    constructor_input = [func for func in abi if func['type'] == 'constructor'][0]['inputs']
    constructor_types = [t['type'] for t in constructor_input]
    input_args = decode_abi(constructor_types, HexBytes(args))
    return input_args

constructor_args = '000000000000000000000000000000000000000000000000000000174876e800000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000a546574686572205553440000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000045553445400000000000000000000000000000000000000000000000000000000'
decoded_args = decode_constructor(constructor_args, TETHER_ABI)
print(decoded_args)
# (100000000000, 'Tether USD', 'USDT', 6)

Happy Easter :)

ghost avatar Apr 17 '22 11:04 ghost

Thanks for recommendation :)

It seems HexBytes has nothing to do with the deployed contract bytecode, so it's still necessary to detect the constructor arguments if tx_input does not contain the bytecode.

kigawas avatar Apr 18 '22 07:04 kigawas

I'm a bit confused by what you mean, what would the input be to reach this part?

I can only think of two cases:

  • you provide the encoded args, then it works like above
  • you provide the whole data field but then also the bytecode, then the arguments are args = data[:len(bytecode)] and you pass that to the same code above

ghost avatar Apr 18 '22 08:04 ghost

I didn't try whether it can eliminate the detection, but I checked the HexBytes code, and it looks like there is no parsing arguments stuff?🤔

kigawas avatar Apr 18 '22 11:04 kigawas

Aah no there is not it's just to convert the string to bytes, but I didn't get why you need to do the parsing yourself

ghost avatar Apr 18 '22 14:04 ghost

eth-abi no longer uses hexbytes

kigawas avatar Nov 22 '24 00:11 kigawas