Solidity

如何創建函式選擇器(方法 ID)

  • December 10, 2019

如 ABI 規範中所述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).

因此,我必須通過 javascript/nodejs/web3js 創建合約函式的**方法 ID (函式選擇器)。**假設我有一組函式名稱及其參數(從 ABI JSON 文件中提取)- 即funcNameAndParams[]。其要素之一如下;

{
 contractNo: 0,
 funcName: 'getSupplyRate',
 params: [ 'address', 'uint256', 'uint256' ]
}
  1. 是否可以生成具有上述資訊的方法 ID?如果是,我該如何繼續?我已閱讀ABI 規範,但找不到如何在 JavaScript/Nodejs/web3.js 中編寫程式碼
  2. 如果我也有契約原始碼,那麼我可以繼續嗎?意味著從 json ABI 生成方法 ID 將很容易還是從 .sol 文件?

使用 web3.js v1.2.x,您可以使用函式web3.eth.abi.encodeFunctionSignature

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

或者簡單地說:

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

在第二個範例中,請注意您應該避免參數類型之間的任何空格。

引用自:https://ethereum.stackexchange.com/questions/78179