0

My smart contract looks like this

contract C {
    uint256 a=50;  //

    function setA(uint256 aval) {
        a = aval;
    }
    function getA() constant returns (uint256) { 
        return a;
    }
 }

I am calling the function asynchronously like this

var a = contract.setA.call(100, function(error, value) {
    .....
});

After that if I call this immediately

var a = contract.getA.call(function(error, value) {
    .....
});

I am getting the same value(50) before the transaction is mined. This is because it needs some time if I want to get the changed value. Is there any way or event so that I get notification that the changed value is updated in blockchain when I can getA to be ensured the current exact value?

1 Answer 1

2

State is not mutated by calls. You need to send a transaction to actually change the value. Then you need to wait for the transaction to be mined before you can read the updated value.

Something like this should work:

function waitForReceipt(hash, cb) {
  web3.eth.getTransactionReceipt(hash, function (err, receipt) {
    if (err) {
      alert(err);
    }

    if (receipt !== null) {
      // Transaction went through
      if (cb) {
        cb(receipt);
      }
    } else {
      // Try again in 1 second
      window.setTimeout(function () {
        waitForReceipt(hash, cb);
      }, 1000);
    }
  });
}

contract.setA.sendTransaction(100, function (error, transactionHash) {
  waitForReceipt(transactionHash, function () {
    contract.getA.call(function (error, value) {
      console.log("New value: " + value.toString());
    });
  });
});

That code is adapted from https://programtheblockchain.com/posts/2017/12/13/building-decentralized-apps-with-ethereum-and-javascript/.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.