Example - Pick a Rarity

The PickRarityExample contract, by extending GeneralRandcastConsumerBase and calling functions from RandcastSDK, demonstrates a system for drawing a rarity level.

// 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 PickRarityExample is GeneralRandcastConsumerBase {
    /* requestId -> randomness */
    mapping(bytes32 => uint256) public randomResults;
    mapping(uint256 => string) public rarityValue;
    uint256 public indexResult;
    uint256[] public rarityWeights = new uint256[](5);
    event RarityValueResult(string);
    constructor(address controller) BasicRandcastConsumerBase(controller) {
        rarityValue[0] = "SSSR";
        rarityValue[1] = "SSR";
        rarityValue[2] = "SR";
        rarityValue[3] = "R";
        rarityValue[4] = "C";

        rarityWeights[0] = 1;  // SSSR(1%)
        rarityWeights[1] = 4;  // SSR(4%)
        rarityWeights[2] = 10; // SR(10%)
        rarityWeights[3] = 20; // R(20%)
        rarityWeights[4] = 65; // C(65%)
    }

    /**
     * Requests randomness
     */
    function getRarity() 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 rarityIndex = RandcastSDK.pickByWeights(randomness, rarityWeights);
        indexResult = rarityIndex;
        emit RarityValueResult(rarityValue[rarityIndex]);
    }
}

This contract also has three important parts: the constructor function, getRarity function, and _fulfillRandomWords function.

In the constructor , the rarityValue is being initialized with five string elements. These values correspond to the rarity levels of certain items or characters: 'SSSR,' 'SSR,' 'SR,' 'R,' and 'C,' each with an index from 0 to 4. The rarityWeights array is initialized with five integer elements representing the weights associated with the rarity levels defined earlier.

The function getRarity is used to request a random number.

_fulfillRandomness calls the RandcastSDK.pickByWeights function which returns an index based on a predefined rarityWeights to determine the rarity of the card drawn in this round. The lower weight corresponds to a lower probability and, therefore, a higher rarity. In this example, 'SSR' is the rarest, with the lowest probability(weight), while 'C' is the most common, with the highest probability(weight).

Last updated