Please follow and like us:

I would like to share my method using in my smart contract to generate random number for Tron dapps

    uint8[] public ranNumbers;    
    function random1(address _add) internal view returns(uint8) {
        //Select one of 27 random number as random factor
        uint randomfactor = now%27;
        uint256 randno = uint256(keccak256(abi.encodePacked(block.timestamp, _add,ranNumbers[randomfactor])));
        return uint8((randno>>(now%8))%100);
    }
    function random27() public {
        //require(Mutexlock);
        require (msg.sender == _owner,'Not Owner');
        Mutexlock = true;
        delete ranNumbers;
        uint256 randno = uint256(keccak256(abi.encodePacked(block.timestamp, now%256)));
        
        for (uint8 i=0;i<27;i++)
        {
            ranNumbers.push(uint8(uint256(randno>>(i*2))%100) );
        }
        emit RandomNumber(randno,ranNumbers);
        Mutexlock = false;
    }

I used several factors to generate the random number including block.timestamp; the current time (now), the user address.

First of all, random27() generates 27 random numbers and saves them in ranNumbers array. This function can be called by any one if needed to create fairness. In this example, I only allow the owner to trigger random27.

The random1() function generates 1 random number using one of the number in ranNumbers array. Its position is selected using:

uint randomfactor = now%27;

I also use alot >> bit shift to mix the random factor around. Thanks for reading and if you have any question, please comment or send me a message

Please follow and like us:
Tron Smart Contract – random number

Leave a Reply

Your email address will not be published. Required fields are marked *

error: Content is protected !!