head over to remix ide. create new solidity file. we will generate random number on rinkeby testnet.
pragma solidity >=0.5.0 <0.9.0;
import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
contract RandomNumber is VRFConsumerBase {
bytes32 internal keyHash;
uint256 internal fee;
uint256 public randomResult;
constructor()
VRFConsumerBase(
0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B, // VRF Coordinator
0x01BE23585060835E02B77ef475b0Cc51aA1e0709 // LINK Token
) public
{
keyHash = 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311;
fee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network)
}
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 {
randomResult = randomness;
}
}
his code can also be views on chainlink official documentations. to gererate random number the gas fee is 0.1 LINK token. so we have to add some link tokens in our smart contract to execute this function. you can get link token from any faucet.
you will have to use respective testnet faucet to get test link tokens. for example this is https://rinkeby.chain.link/ rinkby faucet link.
then you also have to select the respective VRFcoordinator, LINK, nad key hash address which you are using.
for example the below values are given for rinkeby tokens.
Item | value |
LINK | 0x01BE23585060835E02B77ef475b0Cc51aA1e0709 |
VRF Coordinator | 0xb3dCcb4Cf7a26f6cf6B120Cf5A73875B7BBc655B |
Key Hash | 0x2ed0feb3e7fd2022120aa84fab1945545a9f2ffc9076fd6156fa96eaff4c1311 |
Fee | 0.1 LINK |
you can use the respective addresses for the testnets.