1

I'm trying to write a code that reads variable, adds 1, sends update call, waits until the transaction is done and then reads the variable again. Console shows that the transaction is complete, but if I read the variable it gives me the previous result. What is wrong here?

edit

It SOMETIMES displays variable correctly. So there is most likely an async problem somewhere.

Solidity:

pragma solidity ^0.4.22;

contract Test
{
    uint public v;

    function updateV(uint value)
        external
    {
        v = value;
    }
}

JS code:

let rrr = await promisify(cb => contract.v(cb));
rrr = rrr.toNumber();
console.log("received value: " + rrr);
rrr++;
console.log("should return: " + rrr);
let hash = await promisify(cb => contract.updateV(rrr, cb));
await waitForReceipt(hash);
rrr = await promisify(cb => contract.v(cb));
console.log("returns: " + rrr.toNumber());

JS function:

async function waitForReceipt(hash) {
    await new Promise((resolve, reject) => {
        let timer = window.setInterval(function () {
            web3.eth.getTransactionReceipt(hash, function (err, receipt) {
                console.log("check");
                if (err) {
                    clearInterval(timer);
                    reject(err);
                    console.log("nope");
                }

                if (receipt !== null) {
                    clearInterval(timer);
                    resolve(receipt);
                    console.log("ok");
                }
            });
        }, 1000);
    })
}

Console result:

received value: 20
(index):1093 should return: 21
9(index):1068 check
(index):1078 ok
(index):1097 returns: 20
  • Where is this code running? More specifically, what web3 provider are you using? I've seen caching happen in MetaMask before, so if that's what your using, you may have to wait for MetaMask to observe the new block first. – user19510 Jan 23 '19 at 16:21
  • It's a script on my website, I'm using metamask indeed. – Radeg90 Jan 23 '19 at 17:06
  • 1
    The way I avoided the problem on capturetheether.com was to use a separate web3 instance directly connected to Infura for reading. So only writes went through MetaMask. – user19510 Jan 23 '19 at 17:08
  • I just finished solidity code and came back working with the website and implemented your solution. It works perfectly and solved other issue - now users without metamask can see all variables. :) Thanks!! – Radeg90 Feb 6 '19 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.