Blockchain – How to Encode Function Signature and Parameters Using eth_abi

abiblockchainencodingpython

I want to encode a contract's function signature together with parameters and values using python, more explicitely the eth_abi library.


tokenA = "0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c"
tokenB = "0xe9e7cea3dedca5984780bafc599bd69add087d56"

abiEncoded = eth_abi.encode_abi(['address', 'address'], [tokenA, tokenB]).hex()

The code above work perfectly fine for the parameters, and returns an expected result, however I am not sure how to add the leading 4bytes (big-endian encoding) signature inside the hash .

Expected result
0xe6a43905000000000000000000000000bb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c000000000000000000000000e9e7cea3dedca5984780bafc599bd69add087d56

My result
000000000000000000000000bb4cdb9cbd36b01bd1cbaebf2de08d9173bc095c000000000000000000000000e9e7cea3dedca5984780bafc599bd69add087d56

Best Answer

Well, your library doesn't seem to provide a direct equivalent to abi.encodeWithSignature neither of keccak256, the later one is mandatory in order to get the function identifier.

Those 4 bytes that you are looking for are part of what I just talked about : the function identifier. Basically, those are the first 4 bytes of the keccak256 of the function signature.

0xe6a43905 are the first 4 bytes of the keccak256 of : getPair(address,address)

A very minimalist solution using the pysha3 module :

import sha3
k = sha3.keccak_256()
k.update(b'getPair(address,address)')
print (k.hexdigest()[:8])
# OUTPUTS : e6a43905

But you might be better off using Web3py which is up to date, and contains every helper functions that you might need for such a task.