A step-by-step guide to implement Chainlink's Verifiable Random Function (VRF) v2.5 in your smart contracts.
- Consumer Contract: Handles random number requests and fulfillment
- Subscription Management: Prepaid account for VRF usage
- VRF Coordinator: Chainlink's verification and callback system
- Create a consumer contract that inherits from
VRFConsumerBaseV2Plus
- Initialize with your chain's VRF Coordinator address
- Store subscription ID and other configuration parameters
- Create a subscription through Chainlink VRF Dashboard
- Fund subscription with either:
- Native blockchain currency (ETH, MATIC, etc.)
- LINK tokens
- Add consumer contract address to authorized consumers
When calling requestRandomWords
from the VRF Coordinator, provide:
struct RandomWordsRequest {
bytes32 keyHash; // Gas lane identifier
uint256 subId; // Subscription ID
uint16 requestConfirmations; // Block confirmations (typically 3)
uint32 callbackGasLimit; // Gas for fulfillment function
uint32 numWords; // Number of random values needed
bytes extraArgs; // Additional parameters (optional)
}
after requesting the number the coordinator will automatically callback fulfillRandomWords function upon completion the result can be logged in this function