Example - Pick a Property

The PickPropertyExamplecontract illustrates the utilization of GeneralRandcastConsumerBase and RandcastSDK to pick one of several predefined properties.

// 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 PickPropertyExample is GeneralRandcastConsumerBase {
    /* requestId -> randomness */
    mapping(bytes32 => uint256) public randomResults;
    mapping(uint256 => string) public propertyValue;
    uint256 public indexResult;
    event PropertyValueResult(string);
    constructor(address controller) BasicRandcastConsumerBase(controller) {
        propertyValue[0] = "fire";
        propertyValue[1] = "wind";
        propertyValue[2] = "water";

     * Requests randomness
    function getProperty() 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 propertyIndex = RandcastSDK.roll(randomness, 3);
        indexResult = propertyIndex;
        emit PropertyValueResult(propertyValue[propertyIndex]);

The contract structure is similar to the previous example. The main components include the constructor, the function getProperty which is used to request random numbers, and the callback function _fulfillRandomness which is triggered after generating the random number.

In the constructor, define each index to represent the properties of 'fire,' 'wind,' and 'water.'

The function getProperty requests the random number to be used in the callback function.

In the callback function _fulfillRandomnesswe call RandcastSDK.roll to pick the index of the three properties. We can then get the property value by index from the propertyValue mapping.

The reason to choose this RandcastSDK function in this example is that we need to select one of the three properties with equal probability randomly, and RandcastSDK.roll is designed for randomly picking a number within a specified range.

Last updated