0

I'm using web3j in Android studio to interact with smartcontracts.

In my SmartContract i've 2 functions getName() and getAge() and i'm setting age and name in constructor as below:

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.5.0 <0.9.0;

contract Identify {

    string name;
    uint age;

    constructor() public {
        name = "Shoaib Khalid";
        age = 22;
    }

    function getName() view public returns(string memory){
        return name;
    }


    function getAge() view public returns(uint){
        return age;
    }
}

But I'm not able to read the value returned by both functions. After deploying the smartcontract correctly, following is the method I'm trying to read the value returned by getName() function.

  val identityContract = Identity_sol_Identify.load(
            deployedContractAddress,
            web3j,
            getCredentialsFromPrivateKey(),
            DefaultGasProvider.GAS_PRICE,
            DefaultGasProvider.GAS_LIMIT
        )
  Log.d(TAG, "counter Result:  ${identityContract.name.sendAsync().get()}")

Instead of getting the value Shoaib Khalid which I set in the constructor I'm getting a TranscriptReciept object the output screenshoot is attached below. enter image description here

So I want to know can you read the exact value returned by the function getName() in smartcontract using web3j?

Shoaib Kakal
  • 1,090
  • 2
  • 16
  • 32

1 Answers1

0

Please refer to the Web3j documentation:

Transactional calls do not return any values, regardless of the return type specified on the method. Hence, for all transactional methods the Transaction Receipt associated with the transaction is returned [1]
...

The transaction receipt is useful for two reasons:

It provides details of the mined block that the transaction resides in Solidity events that are called will be logged as part of the transaction, which can then be extracted.

You are getting the transaction receipt. In order to query the values from your state variables you should refer to the section Querying the state of a smart contract and do something like this:

Function function = new Function<>(
             "getName", // This is the name of the solidity function in your smart contract
             Collections.emptyList(),  // Solidity Types in smart contract functions, no input in the function so we set this to empty
             Arrays.asList(new TypeReference<Utf8String>() {})); // result will be a string

String encodedFunction = FunctionEncoder.encode(function);
org.web3j.protocol.core.methods.response.EthCall response = web3j.ethCall(
             Transaction.createEthCallTransaction(contractAddress, encodedFunction),
             DefaultBlockParameterName.LATEST)
             .sendAsync().get();

  Iterator<Type> it = someType.iterator();
                Type result = someType.get(0);
                String a = result.toString();
                Log.d("Name: ", a);
IsaacCisneros
  • 1,953
  • 2
  • 20
  • 30