With ethereumjs-abi you can do this to obtain the method identifier of some function:
const id = abi.methodID('balanceOf', ['address'])
and this gives you 70a08231.
Is there a way to do this with @ethersproject/abi? I know I can use the abi to create an interface, but in this particular scenario I literally have the name of the function and the list of types of the inputs.
Thanks!
var abi = [ "function balanceOf(address)"]
var iface = new ethers.utils.Interface(abi)
var id = iface.getSighash('balanceOf');
// '0x70a08231'
const Abi = require('@ethersproject/abi');
const iface = new Abi.Interface(["function balanceOf(address)"]);
console.log(iface.getSighash('balanceOf'));
// 0x70a08231
The downside of these approaches is that I have to manually build a signature. This seems brittle to me, but if it's the only way to do this right now I think I can work with that. Thanks!
How is it brittle?
I was thinking that something like functionName + '(' + types.join(',') + ')' would make me feel unsure, but apparently that's exactly what ethereumjs-abi does, so I guess it's fine? https://github.com/ethereumjs/ethereumjs-abi/blob/1ce6a1d64235fabe2aaf827fd606def55693508f/lib/index.js#L33 :sweat_smile:
I'm closing this issue since I guess this is enough, thank you!
Oh, I read that line too fast, it seems like ethereumjs-abi does other things, like converting ints to int256. I think in our use case that's not necessary, though
Eek! No, you certainly shouldn't do that with strings. I wasn't thinking of "you have an array", more of the "I have a signature". That is certainly brittle.
If you are typing to do something generic with strings, you can try something like:
function getSighash(name, types) {
const fragment = utils.FunctionFragment.from({
type: "function",
constant: true,
name: name,
inputs: types.map(t => utils.ParamType.from(t)
});
return utils.Interface.getSighash(fragment);
}
Given the complexity of that, I think it might make sense to add a utility function to do something similar.
I was always assuming a person usually has access to the ABI fragment, but I guess in some user interfaces you may only have access to the function name and its parameters? Like in development tools?
Thanks @ricmoo!
I was always assuming a person usually has access to the ABI fragment, but I guess in some user interfaces you may only have access to the function name and its parameters? Like in development tools?
Yeah, our scenario is that we are traversing the AST in the JSON output of solc to (among other things) obtain the known selectors, and previous to 0.6 you have to manually build the signature to do this.
Most helpful comment