'Function call work fine in Remix but wont in JS

I've been experiencing trouble to link my chainlink VFR mapping to my Javascript. I've mapped the result of the VRF to the address of the caller so that the result depends on the caller.

Here is the solidity code:

mapping(address => bytes32) private addressToId;
mapping(bytes32 => uint256) private IdToRandom;

function getRandomNumber() public returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
        requestId =  requestRandomness(keyHash, fee);
        addressToId[msg.sender] = requestId;
    }

    function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        IdToRandom[requestId] = randomness;
        getResult();
    }

    function getResult() public view returns (uint randomnombre) {
        randomnombre = IdToRandom[addressToId[msg.sender]];
    }

When I call getResult() in a solidity function to determine if the address won or not, it works fine on remix but won't work on JS.

Here is my JS call:

contract.methods.getResult().call().then(function(bal) { console.log(bal) })

It sends me back 0 and I don't know how to handle it...



Solution 1:[1]

I think you are running into an issue where the getRandomNumber() has been called and that transaction is complete but the callback to fulfillRandomness hasn't occurred yet.

You will need to listen for the event before calling getResult()

One of the methods below should accomplish this

web3: https://web3js.readthedocs.io/en/v1.2.11/web3-eth-contract.html#contract-events

ethers: https://docs.ethers.io/v5/api/providers/provider/#Provider--event-methods

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Richard G