10

There are some similar posts to this but none seem to be able to solve my problem.

I have a contract deployed with Truffle running with testrpc.

I want to access the value of a public uint variable named gameStatus defined in the deployed contract game variable as such:

uint public gameStatus = 23;

I have found two ways to do this:

game.gameStatus(function(err, res){
    document.getElementById('amt').innerText = res;
});

And using the then operator from Promises.

game.gameStatus().then(function(result){
    document.getElementById('tableamt').innerText = result;
});

The first method never affects the value of 'tableamt' in the HTML. And the second method always yields a value of '0' in the HTML.

The contract in both cases deploys without errors and web3 does not complain.

Any help is much appreciated.

Thanks!

max taldykin
  • 2,966
  • 19
  • 27
Carlos G. Oliver
  • 231
  • 1
  • 2
  • 6

4 Answers4

9

To get public variable value you need to use call. It is evaluated directly on local node without sending transaction to the blockchain. See also this great answer.

So, you need to call it that way:

game.gameStatus.call(function(err, res){
    document.getElementById('amt').innerText = res;
});
max taldykin
  • 2,966
  • 19
  • 27
8

It's different now. You should use contractName.methods.varName().call(callback) to access state variables in web3 1.0.0. Solidity compiler automatically creates getters for public state variables.

To answer your question, the method call should be:

game.methods.gameStatus().call(function(err, res){
    //do something with res here
    console.log(res); //for example
};
Jerry Lin
  • 81
  • 1
  • 3
1

This

(await game.gameStatus()).toString()

or this

game.gameStatus().then((x) => x.toString())

works for me.

user66081
  • 131
  • 3
1

A simple promise works just fine.

game.gameStatus().then(function (result) {
    console.log(result);
})

game is the loaded contact, which in my case, I get with another promise.

App.contracts.GameContract.deployed().then(function (game) {
    return game.winningNumbers();
}).then(function (result) {
    console.log(result);
})
typhon04
  • 193
  • 1
  • 7