How to access smart contract's function result?

Hello,
I’m developing a random number dapp via React-Moralis and Chainlik.
I deployed the Chainlink smart contract and i can interact with it via React-Moralis.
I can execute the generating random number function perfectly but i don’t understand how to access the result function and to display it.
I think this is related to my missing knowledge about Javascript objects :slight_smile:
Can you help me please?

Here is the my code:

import React from "react";
import { useWeb3ExecuteFunction } from "react-moralis";

const RandomNumber = () => {
  const interactor = useWeb3ExecuteFunction();

  let options = {
    contractAddress: "PRIVATE",
    functionName: "getRandomNumber",
    abi: [
      {
        inputs: [],
        name: "getRandomNumber",
        outputs: [
          {
            internalType: "bytes32",
            name: "requestId",
            type: "bytes32",
          },
        ],
        stateMutability: "nonpayable",
        type: "function",
      },
      {
        inputs: [
          {
            internalType: "bytes32",
            name: "requestId",
            type: "bytes32",
          },
          {
            internalType: "uint256",
            name: "randomness",
            type: "uint256",
          },
        ],
        name: "rawFulfillRandomness",
        outputs: [],
        stateMutability: "nonpayable",
        type: "function",
      },
      {
        inputs: [],
        stateMutability: "nonpayable",
        type: "constructor",
      },
      {
        inputs: [],
        name: "randomResult",
        outputs: [
          {
            internalType: "uint256",
            name: "",
            type: "uint256",
          },
        ],
        stateMutability: "view",
        type: "function",
      },
    ],
  };

  const interactFunction = async () => {
    await interactor.fetch({
      params: options,
    });
  };

  const showNumber = async () => {
    await interactor.fetch({
      functionName: "randomResult",
    });

  };

  return (
    <div>
      <button onClick={interactFunction}>Generate Random Number</button>
      <button onClick={showNumber}>Show The Random Number</button>
    </div>
  );
};

export default RandomNumber;

1 Like

Are you using the chainlink VRFConsumerbase and VRFRequestIdBase contracts to fetch your random number. If your doing it this way with those contracts then when you request for a random number chainlink fires a callback function when the random number has been generated it may take up to a minute. This means that you can not access the random number in your client immediately from a contract function call. If you want to access the ranomnumber in your front end youll need to emit an event in the callback and then listen for this event in your front end to access the number.

Firstly youll need to create an instance of your smart contract using that abi you have in your code above; to do so you can use

contractInstance = new web3.eth.Contract(abi, contract_address, {from: accounts[0]});

youll need to init web3 first. make a button that calls the function you wrote which uses chainlink to get the random number. then after this listen out for the event fired in the callback when your event gets detected in your client you will have access to the random number.

Again im not sure what method your usinh to detect randomness but if it is this way with the VRF contracts then this is the procedure you need to follow

1 Like

have a look at this

if you follow this guide and get this working then i can explain how to listen for the event in your client

1 Like

Thank you for your answer :slight_smile:
Yes i used the Chainlink VRF in this link: https://docs.chain.link/docs/get-a-random-number/

But i don’t understand what should i use the web3 library? I’m already use Moralis useWeb3ExecuteFunction hook for execute smart contract functions.

So, what i understand is ; getting random number is not instant process and i need to listen that event.

How can i do that?

Thanks again:)

usually you have another function in your smart contract that will be called by chainlink and it will receive that random number

1 Like

Yes it is “randomResult” function but i don’t know how to access that function and display it on the page. This is the main problem :slight_smile:

that function could save the random number in a variable, an later you could call another view function that reads that variable and returns it

1 Like

yea just like catalin says - if a smart contract function changes the state of the blockchain and returns a value - the way to access it is to have a view function on that value

kinda like a “getter” :slight_smile:

2 Likes

If you have it all set up and the smart contract is good in your client alls you need to do is to listen out for the event. if yove followeded the chainlink docs then youll know about the callback that gets fired in your smart contract. this is where the random number is. in your client you can listen for this event uisng something like this. (note that i made up the event name below yours will be different.

 contractInstance.once('generatedRandomNumber', 
        {
            filter: { player: accounts[0] },
            fromBlock: 'latest'
        }, (error, event) => {
        if(error) throw("Error fetching events");

        console.log(event)
        ...
    
        })
        
    });

when your client picks up on this event it willl have access to the random number generated. this event will get emitted in your smart contract after some time when chainlink fetches the random number so. alls u need to do is to listen for it in the frontend with something akin to the above

3 Likes