I just have a simple solidity contract:
pragma solidity ^0.4.19;
contract SampleContract {
string value;
function SampleContract() public {
value = "hello world";
}
function getValue() public view returns (string){
return value;
}
function setValue(string str) public {
value = str;
}
}
I am attempting to interact it with web3j. For now I have already deployed successfully and get the address.
I am trying to call method getValue()
by codes:
static String call(String from, String contractAddress, String callData) throws Exception {
Call call = new Call(from, contractAddress, callData);
return service.ethCall(call, DefaultBlockParameter.valueOf("latest")).send().getValue();
}
String callData = encodeGetValueFuncWithParams();
System.out.println(callData);
String result = call(from, contractAddress, callData);
System.out.println(result);
I indeed get the result but in hex. The result I get is
0x
0000000000000000000000000000000000000000000000000000000000000020
000000000000000000000000000000000000000000000000000000000000000b
68656c6c6f20776f726c64000000000000000000000000000000000000000000
I converted this vaue and it is "hello world" but how can I directly get the value as string "hello world" instead of "0xxxxxxxx".
The way I create my calldata
is shown below:
static String encodeGetValueFuncWithParams(){
Function function = new Function(
"getValue",
Collections.emptyList(),
Arrays.asList(new TypeReference<DynamicBytes>(){})
);
String encodedFunc = FunctionEncoder.encode(function);
return encodedFunc;
}
My question is:
How do I construct my calldata so that I can directly get string value instead of hex value from contract.