0

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.

0

See https://docs.web3j.io/transactions.html#querying-the-state-of-a-smart-contract. I think you need to call FunctionReturnDecoder.decode(). (You'll need to have available the list of output parameter types, so you'll need to restructure your code a bit.)

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.