5

The function to call is called xyz().

My code:

web3.sha3("xyz()").substr(0,10)

Error:

AttributeError: module 'web3' has no attribute 'sha3'

In newer versions of web3, the above error occurs. What else can be used to get the hexadecimal equivalent of the function name?

Source of code: How to know the hex code to use in data to call a specific contract function? (the solution doesn't work on newer versions of web3)

aste123
  • 233
  • 2
  • 8

2 Answers2

3

The hexadecimal equivalent of the method is called the function selector.

The function selector is the first 4 bytes of Keccak hash of the function signature, arguments packed as string types.

You can get this by:

>>> from web3 import Web3
>>> Web3.keccak(text="xyz()")
HexBytes('0x356bc81e51224d094b17ccb8f80b1e659fe334bcf15c6240857cce0568cbb0ba')
>>> hex_bytes = Web3.keccak(text="xyz()")
>>> print(hex_bytes[0:4].hex())
0x356bc81e
Mikko Ohtamaa
  • 22,269
  • 6
  • 62
  • 127
  • 2
    it is also called signature , within the sources it is called signature, but in solidity it is called selector – Nulik Jul 31 '21 at 18:46
  • Thank you @Nulik. I believed the selector refers to Solidity 4-byte identifier whereas the function signature is a general programming language concept. – Mikko Ohtamaa Aug 01 '21 at 11:34
3

you are looking for this:

encodeFunctionSignature

web3.eth.abi.encodeFunctionSignature(functionName);

Encodes the function name to its ABI signature, which are the first 4 bytes of the sha3 hash of the function name including types.

https://web3js.readthedocs.io/en/v1.2.11/web3-eth-abi.html

In pythhon there should exist an equivalent call

Nulik
  • 4,061
  • 1
  • 18
  • 30
  • I have been searching the equivalent for ages but still didn't manage to find it, do you by any chance know it? – CodeNoob Sep 04 '21 at 14:41