[Ethereum] Convert String to Bytes32 Web3.py v4.3 Python

pythonweb3.py

I'm using web3.py v4.x and I have an issue to convert string to bytes32. First I checked out Web3.py conversion APIs. So I used Web3.toBytes but still not working. Kindly check out the below error for more details:

Could not identify the intended function with name `publish`, positional argument(s) of type `(<class 'int'>, <class 'bytes'>, <class 'bytes'>)` and keyword argument(s) of type `{}`.
Found 1 function(s) with the name `publish`: ['publish(uint256,bytes32,bytes32)']
Function invocation failed due to improper argument encoding.

Best Answer

Simply data.encode('utf-8') should be sufficient, if you are converting a string to bytes data.

If your string is more than 32 bytes long after encoding to UTF-8, then your problem is that your contract can't accept the data you want to send.


More background

If a function takes a bytes32, it cannot accept a value longer than 32 bytes. Web3.py will actually reject the function as a possibility based on the type mismatch (because multiple functions with the same name and different types are allowed).

If you have more than 32 bytes to send in, you probably don't want to blindly clip off the end. What you need to do will be highly dependent on the semantics of the contract that you are interacting with.

You do not need to pad the value, Web3.py will handle that for you.

Finally, bytes(str_data, 'utf-8') is equivalent to str_data.encode('utf-8'). Which you prefer is a matter of taste, I suppose, and potentially performance.