Generate a random number using Chainlink

Due to constant issues with the Provable API Oracle I have decided to write a guide to generate a random number using Chainlink.

You can find a great example here: https://docs.chain.link/docs/get-a-random-number

In this example we will use Kovan as testnet.
Keep in mind that your contract must hold Link tokens in order to call the oracle.
You can get Kovan Link tokens here: https://kovan.chain.link/

Let’s now analyse the contract:

    function getRandomNumber(uint256 userProvidedSeed) public returns (bytes32 requestId) {
        require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
        return requestRandomness(keyHash, fee, userProvidedSeed);
    }

This function asks for a parameter called userProvidedSeed, this is a number that can be input by the user manually or by your smart contract automatically. It really depends on you.
The function also returns a requestId as bytes32 that you can/should use to associate the result with the request later on.


    function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        randomResult = randomness;
    }

Whenever the random number is created, it will be sent to your contract by triggering the function fulfillRandomness.
You will receive a bytes32 requestId and the random number randomness.

3 Likes