How to generate random numbers in Solidity using Chainlink VRF?

avatar
Chainlink
3 years ago
This article is approximately 906 words,and reading the entire article takes about 2 minutes
With Chainlink VRF now live on Ethereum mainnet, developers can easily generate random numbers in Solidity in a secure, verifiable manner.

How to generate random numbers in Solidity using Chainlink VRF?

Random number generation (RNG) cannot be done natively in Solidity. To generate a truly verifiable random number on the blockchain, the smart contract must send the seed to an off-chain resource like an oracle, and the oracle must return the random number to the smart contract along with a verifiable proof that Random numbers are generated using a seed. With Chainlink VRF now live on Ethereum mainnet, developers can easily generate random numbers in Solidity in a secure, verifiable manner. In this technical article, we will show you how to use Chainlink VRFGenerate random numbers in Solidity

Chainlink DocumentationChainlink Documentationfound in . Heres a remix on the Kovan testnetGenerate blockchain random numbersexample for those who want to test it now. just remember to followRequest and Receive Methods,useLINK transfer to your smart contractfirst level title

A high-level overview of Chainlink VRF

Chainlink VRF(Verifiable Random Function) is a fair and verifiable source of randomness designed for smart contracts. Solidity developers can use it as a tamper-resistant random number generator to build secure and reliable smart contracts for Ethereum applications that rely on unpredictable outcomes.

seedseed. choose onehard to influence or predictseeds are extremely important. If someone is able to influence or predict the seed, they could theoretically try to collude with the oracle node executing the randomness request to produce an outcome in their favour. Because of this, it is recommended not to use values ​​from the blockchain state, such as block height or block timestamp.

public key cryptographypublic key cryptographycreated, which is a widely used technique in blockchain technology. Importantly, the results can be verified, preventing participants such as miners or oracles from influencing the random number results for their own benefit.

Heres a high-level overview of how Chainlink VRF works. More details about the underlying technical implementation can be found in ourIntroduction to Chainlink VRFfound in . However, as a developer, you dont need to worry about anything other than getting the seed and then creating a request to the Chainlink oracle.

Create a consumer contract

How to get a random number in a Solidity smart contract, we should first get a random number from ChainlinkVRFConsumerBasecontract inheritance. The consumer contract should also contain variables to store the nonce result, the public key hash used to generate the randomness, and a fee to pay the oracle for fulfilling the request.

How to generate random numbers in Solidity using Chainlink VRF?

Contract addressContract addresspartially obtained. Finally, we need to set the payment amount of LINK token. For the Kovan test environment, it is 0.1 LINK.

How to generate random numbers in Solidity using Chainlink VRF?

Next, we rewrite two functions `getRandomNumber` and `fulfillRandomness` in the contract. The `getRandomNumber` function should take the seed as an input parameter, and call the `requestRandomness` function in VRFConsumerBase, passing the keyHash, the fee amount, and the given seed as parameters.

How to generate random numbers in Solidity using Chainlink VRF?

When executed, this function sends a request to a given VRF coordinator contract, then builds a final seed and sends it to that VRF coordinators Chainlink oracle. The final seed is built with a hash of the following values.

- User-supplied torrents

- The hash of the public key of the Chainlink oracle that satisfied the request

- the user nonce when requested

- The address of the contract making the request

- current block number

The reason for using these extra values ​​is to prevent a contract from using the same seed more than once to get the same result. The nonce helps prevent contracts from making multiple requests within the same block, so in theory, contracts could use the same seed to request multiple nonces within the same block, and they would still get a uniquely valid nonce for each request. Authentication nonce.

The `fulfillRandomness` function accepts the random number response parameter as an unsigned integer, and the ID of the request, and then stores the given random number in the contract. This function is called when the VRFCoordinator contract receives and verifies a random number. More information on these two functions can be found atfound in .found in .

How to generate random numbers in Solidity using Chainlink VRF?

Now that we have a complete and working random number generation (RNG) example in Solidity, we can deploy and test the contract.

complete contract

abovecomplete contractIt can be easily opened in Remix, compiled, and deployed on the Kovan network. After deployment, you must transfer some LINK to the contract.

Once the contract has at least 0.1 LINK funded, we can call the `getRandomNumber` function, passing in a number as the seed. This will send the request along with the seed to the VRF coordinator running on the Chainlink oracle.

How to generate random numbers in Solidity using Chainlink VRF?

After the transaction is processed, we need to wait a few seconds for the Chainlink oracle to complete the request for the random number, and then call the fulfillRandomness function we created earlier to return the random number to our consumer contract.

first level title

How to generate random numbers in Solidity using Chainlink VRF?

Verify randomness

Now that we have a nonce returned to our contract, you might be wondering, how can we be sure that it was generated by a given seed and public key hash of the Chainlink oracle that performed the request. When using Chainlink VRF, the answer is that you dont need to. Verification happens automatically as part of the `VRFCoordinator` contract completion request.

If the verification fails, the nonce is not returned to the consumer contract and the transaction is reverted. Therefore, blockchain developers using Chainlink VRF can rest assured that the random numbers they get through Chainlink VRF are verifiable random numbers. For the underlying technical details of verification, please refer to ourSummarize

Summarize

Chainlink VRF helps Solidity developers quickly and easily generate random numbers in smart contracts in a safe, secure and verified manner.

Original article, author:Chainlink。Reprint/Content Collaboration/For Reporting, Please Contact report@odaily.email;Illegal reprinting must be punished by law.

ODAILY reminds readers to establish correct monetary and investment concepts, rationally view blockchain, and effectively improve risk awareness; We can actively report and report any illegal or criminal clues discovered to relevant departments.

Recommended Reading
Editor’s Picks