简体   繁体   中英

web3 instantly firing callback

not sure if I should post this on the Ethereum SE but I have a feeling it is more javascript related, so I'll try here:

I have a very simple smart contract that consists of essentially just a getNum function and a setNum function. The smart contract can be viewed here: https://pastebin.com/ci6mbPDq

I am trying to construct a simple frontend to call it. Essentially, I follow this guide . A working codepen of my frontend (demonstrating the janky functionality) can be found here: https://codepen.io/heh/pen/PeMmKe As you can see in my codepen, I call my getNum function like:

BasicToken.getNum(0x64319ca297239d8652a0b5f0f12dd6666cb0e05b,

        function(error, result)
        {
            console.log(result.toNumber());
            document.getElementById("target").innerText = result.toNumber();

        }
    );

However, I keep getting "0" as the result. On the other hand, my setNum function is able to post a result to the Ropsten blockchain. However, I notice that both function calls seem to be firing off their callback instantly.

Could anyone help me figure out why the function calls return instantly?

Thanks!

The callback is not being called immediately, the problem is you're not sending an actual address, which should be a string, and you're sending a number:

0x64319ca297239d8652a0b5f0f12dd6666cb0e05b == 5.720054584403591e+47

And you get 0 because that invalid address you're sending doesn't exist in the mapping:

mapping (address=>uint) map23;

And if it doesn't exist it will return the default value for uint which is zero.

Send a string and it will work:

BasicToken.getNum('0x64319ca297239d8652a0b5f0f12dd6666cb0e05b', () => {})

Furthermore, if you only want the current user to retrieve their own value, and not let other users retrieve that data (They can, since it's public, but not that easy), you should use msg.sender and drop the function parameter.

function getNum() public view returns (uint) {
   return map23[msg.sender];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM