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?

  • 1
    The arguments you describe seem straightforward. What did you try, and where did you run into trouble? – user19510 Jan 5 '19 at 10:50
  • I did not try this yet, because there is no documentation for this method I would like to know what stays for 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

Use contract.selector


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']) 

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.