Example - Pick a Winner

The PickWinnerExample contract, inheriting GeneralRandcastConsumerBase and calling functions in RandcastSDK, implements the functionality to pick a winner between two players.

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

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

contract PickWinnerExample is GeneralRandcastConsumerBase {
    /* requestId -> randomness */
    mapping(bytes32 => uint256) public randomResults;
    uint256 public indexResult;
    mapping(uint256 => string) public indexToName;
    event WinnerResult(string);

    constructor(address controller) BasicRandcastConsumerBase(controller) {
        indexToName[0] = "player1 win";
        indexToName[1] = "player2 win";
        indexToName[2] = "tie";
    }

    /**
     * Requests randomness
     */
    function getWinner() external returns (bytes32) {
        bytes memory params;
        return _requestRandomness(RequestType.Randomness, params);
    }

    /**
     * Callback function used by Randcast Adapter
     */
    // solhint-disable-next-line
    function _fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
        randomResults[requestId] = randomness;
        uint256 winnerIndex = RandcastSDK.roll(randomness, 3);
        indexResult = winnerIndex;
        emit WinnerResult(indexToName[winnerIndex]);
    }
}

The three important components of the contract are the constructor function, getWinner function and the callback function _fulfillRandomness.

Inside the constructor, we set the value of indexToName, this variable maps the indices to strings denoting the outcome of a game (Player 1 wins, player 2 wins, or tie).

The function getWinner is used to request a random number.

In the callback function _fulfillRandomness, we use the random number requested earlier to call the RandcastSDK.roll function. This gives us a random index between 0 and 2. This index corresponds to the win/loss result defined in indexToName.

In this example, the probability of player 1 and player 2 winning, losing, or tying are the same. Therefore, we can use the RandcastSDK.roll function to decide the outcome of the game randomly.

Last updated