Search code examples
ethereumblockchainsoliditysmartcontractschainlink

Getting a random number with Chainlink VRF


I'm trying to generate a random number with Chainlink VRF for a raffle system. This number should have a maximum value of ticketOwners.length and a minimum of 0, as I'll be getting the index of the array to pick as winner.

I currently have this code, which returns uint256: 0 whenever calling getRandomNumber(). Aside from the vulnerabilities of this code I'm solely looking for help on generating this number.

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.17;

import "https://github.com/smartcontractkit/chainlink/blob/develop/contracts/src/v0.8/VRFConsumerBase.sol";

contract Random is VRFConsumerBase {
    bytes32 internal immutable keyHash;
    uint256 internal immutable fee;
    uint256 public immutable ticketPrice;

    uint256 public result;
    address payable[] public ticketOwners;

    constructor (
        address _ChainlinkVRFCoordinator,
        address _ChainlinkLINKToken,
        bytes32 _ChainlinkKeyHash,
        uint256 _ticketPrice
    ) VRFConsumerBase (
        _ChainlinkVRFCoordinator,
        _ChainlinkLINKToken
    ) {
        keyHash = _ChainlinkKeyHash;
        fee = 0.1 * 10 ** 18;
        ticketPrice = _ticketPrice;
    }

    function enterRaffle() public payable {
        require(msg.value >= ticketPrice, "Invalid ticket price");
        ticketOwners.push(payable(msg.sender));
    }

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

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

Solution

  • You probably using incorrect addresses for the parameters. Chainlink has two main variations. Since you are using VRFConsumerBase this is VRf V1, you can get addresses from here. I used those for goerli:

    link address           = 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
    key hash               = 0x0476f9a745b61ea5c0ab224d3a6e4c99f0b02fce4da01143a4f70aa80ae76e8a
    
    ChainlinkVRFCoordinator= 0x2bce784e69d2Ff36c71edcB9F88358dB0DfB55b4
    

    After you deploy the contract, you have to send link token to the contract, because you need to pay for the fee parameter that you set. link token faucet

    You press on getRandomNumber button and you need to wait a little bit upto a minute. then your result value be set

    here is the proof work:

    enter image description here