1
votes

I am trying to get the value of a variable in a Smart Contract using solidity, geth and web3j.

The contract HelloWorld is very simple:

pragma solidity ^0.6.10;
   contract HelloWorld {
   uint256 public counter = 5;
  
   function add() public {  //increases counter by 1
       counter++;
   }
 
   function subtract() public { //decreases counter by 1
       counter--;
   }
   
   function getCounter() public view returns (uint256) {
       return counter;
   }
}

web3j does not have a call() function, just only send() which is surprising.

when I try get counter following the web3j instructions:

contract.getCounter().send()

I get a transaction receipt rather than the value uint256.

Can anybody help?

Thank you

Will

1
Web3Js does have a call method. To call your getCounter() method use this syntax : contract.methods.getCounter().call()...Emmanuel Collin

1 Answers

0
votes

You need to modify the getCounter() function in the generated HelloWorld.java file.

public RemoteCall<Type> getCounter() {
    final Function function = new Function(
            FUNC_GETCOUNTER, 
            Arrays.<Type>asList(), 
            Arrays.<TypeReference<?>>asList(new TypeReference<Uint>() {}));
    return executeRemoteCallSingleValueReturn(function);
}

And to get the value, use the following code :

Type message = contract.getCounter().send();
System.out.println(message.getValue());