Skip to content

Instantly share code, notes, and snippets.

@jdnichollsc
Last active March 18, 2024 15:16
Show Gist options
  • Save jdnichollsc/a1db772a575cc968bc96355961c3d60e to your computer and use it in GitHub Desktop.
Save jdnichollsc/a1db772a575cc968bc96355961c3d60e to your computer and use it in GitHub Desktop.
Create a Random Number with Chainlink
// SPDX-License-Identifier: MIT
pragma solidity 0.8.21;
import {VRFCoordinatorV2Interface} from "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol";
import {VRFConsumerBaseV2} from "@chainlink/contracts/src/v0.8/vrf/VRFConsumerBaseV2.sol";
import {ConfirmedOwner} from "@chainlink/contracts/src/v0.8/shared/access/ConfirmedOwner.sol";
// Fuji Testnet: 0xb9477bfbCAe729643b8251404Fa6E4356bB3d9A3
contract RandomNumber is VRFConsumerBaseV2 {
VRFCoordinatorV2Interface COORDINATOR;
uint256 public s_latestRandomValue;
struct RequestStatus {
bool fulfilled; // whether the request has been successfully fulfilled
bool exists; // whether a requestId exists
uint256[] randomWords;
}
mapping(uint256 => RequestStatus)
public s_requests; /* requestId --> requestStatus */
bytes32 keyHash;
uint64 s_subscriptionId; /* https://vrf.chain.link/ */
uint16 requestConfirmations;
uint32 callbackGasLimit;
constructor(
address vrfCoordinator, /* https://docs.chain.link/vrf/v2/subscription/supported-networks#avalanche-fuji-testnet */
bytes32 _keyHash,
uint64 _subscriptionId, /* https://vrf.chain.link/ */
uint16 _requestConfirmations,
uint32 _callbackGasLimit
) VRFConsumerBaseV2(vrfCoordinator) {
COORDINATOR = VRFCoordinatorV2Interface(vrfCoordinator);
keyHash = _keyHash;
s_subscriptionId = _subscriptionId;
requestConfirmations = _requestConfirmations;
callbackGasLimit = _callbackGasLimit;
}
function requestRandomness(uint32 numWords) external returns(uint256 requestId) {
requestId = COORDINATOR.requestRandomWords(
keyHash,
s_subscriptionId,
requestConfirmations,
callbackGasLimit,
numWords
);
s_requests[requestId] = RequestStatus({
randomWords: new uint256[](0),
exists: true,
fulfilled: false
});
}
function fulfillRandomWords(
uint256 _requestId,
uint256[] memory _randomWords
) internal override {
require(s_requests[_requestId].exists, "request not found");
s_requests[_requestId].fulfilled = true;
s_requests[_requestId].randomWords = _randomWords;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment