Solidity

你能得到一個隨機數數組嗎?

  • August 9, 2021

這個問題說明了一切。我可以得到一組可靠的隨機數嗎?

由於區塊鍊是確定性的,因此獲得一個可靠的隨機數本身就很棘手。你會想要到達區塊鏈之外,但只能使用可以證明它們的數字是隨機的服務。為此,您需要使用Chainlink VRF並返回整個數組。

然後,您可以創建一個expand函式,即基於種子隨機數的整個隨機數數組。

function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues) {
   expandedValues = new uint256[](n);
   for (uint256 i = 0; i < n; i++) {
       expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
   }
   return expandedValues;
}

就上下文而言,這是 kovan 測試網上的完整合約的樣子:


pragma solidity 0.6.6;

import "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";

/**
* THIS IS AN EXAMPLE CONTRACT WHICH USES HARDCODED VALUES FOR CLARITY.
* PLEASE DO NOT USE THIS CODE IN PRODUCTION.
*/
contract RandomNumberConsumer is VRFConsumerBase {
   
   bytes32 internal keyHash;
   uint256 internal fee;
   
   uint256 public randomResult;
   
   /**
    * Constructor inherits VRFConsumerBase
    * 
    * Network: Kovan
    * Chainlink VRF Coordinator address: 0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9
    * LINK token address:                0xa36085F69e2889c224210F603D836748e7dC0088
    * Key Hash: 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4
    */
   constructor() 
       VRFConsumerBase(
           0xdD3782915140c8f3b190B5D67eAc6dc5760C46E9, // VRF Coordinator
           0xa36085F69e2889c224210F603D836748e7dC0088  // LINK Token
       ) public
   {
       keyHash = 0x6c3699283bda56ad74f6b855546325b68d482e983852a7a82979cc4807b641f4;
       fee = 0.1 * 10 ** 18; // 0.1 LINK (Varies by network)
   }
   
   /** 
    * Requests randomness 
    */
   function getRandomNumber() public returns (bytes32 requestId) {
       require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK - fill contract with faucet");
       return requestRandomness(keyHash, fee);
   }

   /**
    * Callback function used by VRF Coordinator
    */
   function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
       randomResult = randomness;
   }

   // function withdrawLink() external {} - Implement a withdraw function to avoid locking your LINK in the contract

function expand(uint256 randomValue, uint256 n) public pure returns (uint256[] memory expandedValues) {
   expandedValues = new uint256[](n);
   for (uint256 i = 0; i < n; i++) {
       expandedValues[i] = uint256(keccak256(abi.encode(randomValue, i)));
   }
   return expandedValues;
}
}

引用自:https://ethereum.stackexchange.com/questions/106843