Last active
October 20, 2022 09:28
-
-
Save tntdev21/025b0c69d35761c7197cba926d39eb52 to your computer and use it in GitHub Desktop.
The random function on solidity, read more in Vietnamese: https://nhatky.dev/2022/10/20/minh-dang-dung-ham-solidity-random-number-nhu-nay
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// SPDX-License-Identifier: MIT | |
pragma solidity 0.8.0; | |
import "./libs/zeppelin/token/BEP20/IBEP20.sol"; | |
interface ILPToken is IBEP20 { | |
function getReserves() external view returns (uint, uint); | |
} | |
contract TestRandom { | |
string private seed; | |
ILPToken[] private lpTokens; | |
event Success(bool success); | |
modifier notContract() { | |
require(msg.sender.code.length == 0, "Contract not allowed"); | |
_; | |
} | |
constructor(string memory _seed, address _token1, address _token2, address _token3) { | |
seed = _seed; | |
lpTokens.push(ILPToken(_token1)); | |
lpTokens.push(ILPToken(_token2)); | |
lpTokens.push(ILPToken(_token3)); | |
} | |
function foo() external notContract() { | |
uint8 random = _genRandomNumberInRange(seed, _getDexSeed(), 0, 99); | |
emit Success(random < 7); | |
} | |
function _getDexSeed() private view returns (uint) { | |
(uint reserve00, uint reserve10) = lpTokens[0].getReserves(); | |
(uint reserve01, uint reserve11) = lpTokens[1].getReserves(); | |
(uint reserve02, uint reserve12) = lpTokens[2].getReserves(); | |
return reserve00 + reserve10 + reserve01 + reserve11 + reserve02 + reserve12; | |
} | |
function _genRandomNumberInRange(string memory _seed, uint _dexRandomSeed, uint _from, uint _to) private view returns (uint8) { | |
require(_to > _from, 'TestRandom: Invalid range'); | |
uint randomNumber = uint( | |
keccak256( | |
abi.encodePacked( | |
keccak256( | |
abi.encodePacked( | |
block.number, | |
block.difficulty, | |
block.timestamp, | |
msg.sender, | |
_seed, | |
_dexRandomSeed | |
) | |
) | |
) | |
) | |
) % (_to - _from + 1); | |
return uint8(randomNumber + _from); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment