计算合约方法的签名
通过智能合约实现
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.26;
contract FunctionSelector {
/*
"transfer(address,uint256)"
0xa9059cbb
"transferFrom(address,address,uint256)"
0x23b872dd
*/
function getSelector(string calldata _func)
external
pure
returns (bytes4)
{
return bytes4(keccak256(bytes(_func)));
}
}
部署合约,然后传入对应方法的签名,执行getSelector,就可以获得输出。
通过web3j实现
@Test
public void buildErc20MethodId_transferFrom(){
String from = "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4";
String to = "0x5B38Da6a701c568545dCfcB03FcB875f56beddC4";
BigDecimal amount = BigDecimal.TEN;
// 构建方法调用信息 transferFrom(address,address,uint256)
String method = "transferFrom";
// 构建输入参数
List<Type> inputArgs = new ArrayList<>();
inputArgs.add(new Address(from));
inputArgs.add(new Address(to));
inputArgs.add(new Uint256(Convert.toWei(amount, Convert.Unit.WEI).toBigInteger()));
// 合约返回值容器
List<TypeReference<?>> outputArgs = new ArrayList<>();
String funcABI = FunctionEncoder.encode(new Function(method, inputArgs, outputArgs));
System.out.println(funcABI);
Assert.assertEquals("0x23b872dd", funcABI.substring(0, 10));
}