使用java-sdk从solidity合约中获取返回值问题
长安链版本是v2.3.0,使用的java-sdk版本是2.3.0,web3j版本是5.0.0. 合约源码:
pragma solidity ^0.5.0;
contract TestStr {
function getVersion() public view returns( string memory){
return "1.0.0";
}
}
合约二进制:608060405234801561001057600080fd5b5061013f806100206000396000f3fe608060405260043610610041576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff1680630d8e6e2c14610046575b600080fd5b34801561005257600080fd5b5061005b6100d6565b6040518080602001828103825283818151815260200191508051906020019080838360005b8381101561009b578082015181840152602081019050610080565b50505050905090810190601f1680156100c85780820380516001836020036101000a031916815260200191505b509250505060405180910390f35b60606040805190810160405280600581526020017f312e302e3000000000000000000000000000000000000000000000000000000081525090509056fea165627a7a72305820f220d111cbe35247412c55054cb47c96dab44510d011c7645ff587996981c4cf0029
java代码实现:
HashMap<String, byte[]> getVersionParam = new HashMap<>();
Function getVersionFunc = new Function("getVersion", Collections.<Type>emptyList(), Arrays.<TypeReference<?>>asList(new TypeReference<Utf8String>() {
}));
String getVersionEncode = FunctionEncoder.encode(getVersionFunc);
String method = getVersionEncode.substring(0, 10);
getVersionParam.put("data", getVersionEncode.getBytes(Charset.defaultCharset()));
ResultOuterClass.TxResponse txResponse = chainClient.invokeContract("TestStr", method, null, getVersionParam, 1000 * 10, 1000 * 10);
System.out.println(txResponse.getContractResult().getResult().toStringUtf8());
String hexString = Hex.toHexString(txResponse.getContractResult().toByteArray());
System.out.println("hex string:" + hexString);
List<Type> decode = FunctionReturnDecoder.decode(hexString, getVersionFunc.getOutputParameters());
从ContractResult中获取的值为 1.0.0
计算出的hex string为126000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000005312e302e3000000000000000000000000000000000000000000000000000000020eb08,调用decode方法获取不到值