2

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](https://web3js.readthedocs.io/en/v1.2.7/web3-eth-contract.html#id26). To call your getCounter() method use this syntax : `contract.methods.getCounter().call()...` – Emmanuel Collin Jul 23 '20 at 08:21

1 Answers1

2

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()); 
dev13
  • 21
  • 2