Solidity的随机数

Solidity语言不提供随机数的相关函数,如果要使用随机数,要么使用第三方服务,要么自己生成伪随机数。我们在编写智能合约的适合,必须考虑使用场景:

场景一:批量创建随机数

    function generateRandoms(uint256 count, uint256 maxValue) public view returns (uint256[] memory result) {
        result = new uint256[](count);
        uint256 randomHash = uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.coinbase, gasleft())));

        for (uint256 i = 0; i < count; i++) {
            result[i] = randomHash % maxValue;
            randomHash = (randomHash > block.number) ? (randomHash - block.number) : (block.number - randomHash);
        }
    }

场景二:每次获取一个不同ID

    uint256 constant MAX_POPULATION = 10;
    uint256[] ids = new uint256[](MAX_POPULATION);

    function pickId() public returns (uint256 id) {
        require(ids.length > 0, "no id left");

        // generate random hash and use it to pick a number between 0 and ids.length
        uint256 randomIndex = uint256(keccak256(abi.encodePacked(msg.sender, block.timestamp, block.coinbase, gasleft()))) % ids.length;

        // use current index or grab an old one
        id = (ids[randomIndex] != 0) ? ids[randomIndex] : randomIndex;

        // fill array position with value
        uint256 lastPos = ids.length - 1;
        ids[randomIndex] = (ids[lastPos] == 0) ? lastPos : ids[lastPos];

        // shrink ids array
        ids.pop();
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值