Example - Draw a Lottery

The DrawLotteryExample illustrates the utilization of GeneralRandcastConsumerBase and RandcastSDK to construct a straightforward lottery system.

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

import {
} from "randcast-user-contract/user/GeneralRandcastConsumerBase.sol";
// solhint-disable-next-line no-global-import
import "randcast-user-contract/user/RandcastSDK.sol" as RandcastSDK;

contract DrawLotteryExample is GeneralRandcastConsumerBase {
    /* requestId -> randomness */
    mapping(bytes32 => uint256[]) public randomResults;
    uint256[] public winnerResults;
    uint32 public ticketNumber;
    uint32 public winnerNumber;

    // solhint-disable-next-line no-empty-blocks
    constructor(address adapter) BasicRandcastConsumerBase(adapter) {}
    event LotteryTicketGenerated(uint256[] ticketResults);
     * Requests randomness
    function getTickets(uint32 ticketNum, uint32 winnerNum) external returns (bytes32) {
        ticketNumber = ticketNum;
        winnerNumber = winnerNum;
        bytes memory params = abi.encode(ticketNumber);
        return _requestRandomness(RequestType.RandomWords, params);

     * Callback function used by Randcast Adapter
    function _fulfillRandomWords(bytes32 requestId, uint256[] memory randomWords) internal override {
        randomResults[requestId] = randomWords;
        emit LotteryTicketGenerated(randomWords);
        winnerResults = RandcastSDK.draw(randomWords[randomWords.length - 1], randomWords, winnerNumber);

    function lengthOfWinnerResults() public view returns (uint256) {
        return winnerResults.length;

    function getTicketResults(bytes32 requestId) public view returns (uint256[] memory) {
        return randomResults[requestId];

The contract structure is similar to the previous example:

It first issues a random number request, setting the request type toRequestType.RandomWord, and sets params for the length of the returned array (the total number of lottery tickets). Upon receiving the tickets in the form of an array, in the _fulfillRandomWords function, we call the RandcastSDK.draw method to randomly pick a subset of elements based on their index positions in the array representing the winners.

If you want to draw a subset of elements from an existing array, consider requesting a single randomness by using _requestRandomness(RequestType.Randomness, params) and then calling draw(randomness, indices, winnerNumber).

Last updated