3

I am making a simple decompiler but i'm struggling with encoding my functions to signatures. For instance I have function "transfer(address recipient, uint256 amount)" which I want to encode into a 4 byte signature also known as MethodID, which for transfer is 0xa9059cbb. Is there a way to do it? I'm using ethers.js.

3 Answers 3

4

You can use the ethers.utils.id function.

const { utils } = require('ethers')

console.log(utils.id('transfer(address,uint256)').substring(0, 10))

The utils.id function will return the keccak256 hash of the function signature you passed it. The substring function call is used to extract 0x + first four bytes. So the final data is the method ID you're looking for.

https://docs.ethers.io/v5/api/utils/hashing/#utils-id

2
const iface = new ethers.utils.Interface(abi)
const selector = iface.getSighash('transfer')

You can also get the interface from the Contract object: const iface = contract.interface.

If there is ambiguity in the function, then you'll have to add the parameters for getSighash: const selector = iface.getSighash('transfer(address recipient, uint256 amount)'), ethers will find the correct function for you.

0

In ethers v6:

  const selector = ethers.FunctionFragment.getSelector('mint', ['address', 'uint256']) // '0x40c10f19'

You don't need the ABI to get a function selector.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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