1

As stated in ABI specs that 0xcdcd77c0: the Method ID. This is derived as the first 4 bytes of the Keccak hash of the ASCII form of the signature baz(uint32,bool).

So, I have to create method IDs (function selectors) of my contract functions through javascript/nodejs/web3js. Suppose i have an array of functions name and their parameters (extracted from ABI JSON file)- i.e. funcNameAndParams[]. One of its element is as follow;

{
  contractNo: 0,
  funcName: 'getSupplyRate',
  params: [ 'address', 'uint256', 'uint256' ]
}
  1. Is it possible to generate Method IDs, having above information ? if yes, how could i proceed ? I have read ABI specs but could not found how to code it in JavaScript/Nodejs/web3.js
  2. If I have contract source code as well, then could i proceed ? Means generating Methods IDs from json ABIs will be easy or from .sol file ?
2

With web3.js v1.2.x, you can use function web3.eth.abi.encodeFunctionSignature:

const selector = web3.eth.abi.encodeFunctionSignature({
    type: "function",
    name: yourObj.funcName,
    inputs: yourObj.params.map(param => ({type: param}))
});

Or simply:

const selector = web3.eth.abi.encodeFunctionSignature("getSupplyRate(address,uint256,uint256)");

In the second example, note that you should avoid any spaces between the parameter types.

  • thanks a lot... works for me... – Amir Ali Dec 10 '19 at 12:40
  • @AmirAli: NP :) – goodvibration Dec 10 '19 at 12:44

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.