I want to encode the parameters needed to call a contract method.
In web3js I would use web3.eth.abi.encodeParameters(types, values);
I need to do the same in python I found a function called encodeABI()
which takes arguments: fn_name, args=None, kwargs=None, data=None
Unfortunately the documentation for this method is missing. So my question is how to encode these parameters using web3py?
Use contract.selector
Example:
For get contract use this code:
def getInfo(abi, address):
api = w3.eth.contract(address=address, abi=abi)
return api
def contractFunction(address, param1, param2):
abi = """
json abi code
"""
return getInfo(abi, address).functions.contractFunction(param1, param2)
And when you make sign transactions, in data you may use this code:
'data': str(contractFunction(contract, param1, param2).selector)
+ param1.rjust(64, '0')
+ param2.rjust(64, '0')
There contract is first 4 symbols of hash contract function with parameter, and other symbols is symbols, appended to 64 symbols with 0
It seems that you should do:
my_contract.encodeABI (fn_name='my_method', args=[arg1, arg2, ...])
This is similar to Web3js:
myContract.methods.myMethod.encodeABI (arg1, arg2, ...)
See details in documentation.
You can use the eth-abi library.
>>> from eth-abi import encode_abi
>>> encode_abi(['bytes32', 'bytes32'], [b'a', b'b'])
b'a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00b\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
args, kwargs
and why I need to specify the function name when in web3js it's not needed – Marcello Bardus Jan 5 '19 at 14:39