Pseudorandom numbers are used in applications like lotteries, gaming, and even random selection in NFT sales/giveaways. In some cases, it is necessary to prove to third parties that a random number was generated without the influence or control of a user/application. With Hedera, you have a transaction and Solidity library available to generate pseudorandom numbers with just a few lines of code. This means that when your application generates a random number, anyone can verify that the number was truly generated by the Hedera network – without being influenced by any one user. In this tutorial, you will learn how to generate random numbers on Hedera using the JavaScript SDK and Solidity. Keep in mind that the random number generator covered here is secure enough for practical applications, but you should carefully consider whether it is secure enough for your specific purpose. For details on limitations and security considerations, see HIP-351 (special mention and thanks to LG Electronics for the help and input in formulating this Hedera Improvement Proposal). This resource is helpful if you want to learn more about the difference between pseudorandom and random numbers. For simplicity, we’ll use both terms interchangeably throughout this tutorial.Documentation Index
Fetch the complete documentation index at: https://hedera-0c6e0218-mintlify-enhance-hollow-account-docs-97196.mintlify.app/llms.txt
Use this file to discover all available pages before exploring further.
Prerequisites
- Get a Hedera Testnet account here.
- Get the example code from GitHub.
- Set up your environment and create a client here.
Table of Contents
Generate Random Numbers Using the SDK
Step 1: The Operator is the only account involved in submitting transactions to the Hedera network. Your testnet credentials from the Hedera portal should be used for the operator variables, which are used to initialize the Hedera client that submits transactions to the network and gets confirmations.- The constants lo and hi are the lower and upper limits for the random number, respectively
- Generate a random number (randomNum) 5 times with a for loop
- Use PrngTransaction() in the SDK to create a transaction that generates a pseudorandom number
- If a positive value is provided to the setRange() method, then the transaction record will contain a 32-bit pseudorandom integer that is equal or greater than 0 and less than hi
- If a range is not specified, then the transaction record contains the 384-bit array of pseudorandom bits
- The client is used to execute the transaction and obtain the transaction record
- Output to the console the random number for each loop run
index.js
Console Output ✅
Console Output ✅
STEP 1 ===================================- Generating random numbers with the SDK…- Run #1: Random number = 10- Run #2: Random number = 7- Run #3: Random number = 14- Run #4: Random number = 44- Run #5: Random number = 27
Generate Random Numbers Using Solidity
Step 2: Deploy a Solidity smart contract to generate the random number. After completing all steps, your console should look something like this.Deploy Contract
In theindex.js file:
- Set the gas limit (gasLim) to be 4,000,000 and define the contract bytecode
- Deploy the contract using the helper function contracts.deployContractFcn
- The function returns the contractId in Hedera format and contractAddress in Solidity format
- The inputs are the bytecode, gasLim, and client
- Output to the console contractId and contractAddress
Execute Contract
- Use the helper contracts.executeContractFcn to execute the contract function getPseudorandomNumber
- Use ContractFunctionParameters() from the SDK to specify the parameters for the contract function (randNumParams). Pass the lower (lo) and upper (hi) limits for the random number
- The inputs are the contract ID (contractId), the contract function to execute, randNumParams, gasLim, and client
- The contract function calls a precompiled contract and gets the bytes for the random seed. The random number is calculated, stored in the state variable randNum, and returned by the function
- The helper function returns the record object of the transaction (randNumRec), which is used to obtain the status of the transaction
- Output to the console:
- The status of the contract call
Query Results
You will learn various ways to obtain the random number from the Solidity contract. The best approach depends on your use case and preference. You can get the random number by: using a transaction record, doing a contract call to read state variables, and checking a mirror node explorer.- Use the helper function queries.txRecQueryFcn to obtain information from the transaction record
- The function returns a record query object (recQuery)
- The inputs are the ID of the relevant transaction from the record object (randNumRec.transactionId) and client
- The query of the transaction record, recQuery, was configured to return information on child transactions. Thus, the first child transaction of the contract execution (parent transaction) contains information about the bytes needed for the random number – see recQuery.children[0].prngBytes
- The random number is obtained from doing a modulo operation (%) of the integer value of the last four bytes and the specified range
- Use the helper contracts.callContractFcn to call the contract function getNumber, which reads the random number from a state variable in the contract
- The inputs are contractId, the contract function to call, gasLim, and client
- The helper function returns randNumResult, which is used to obtain the random number
- Use the helper function queries.mirrorTxQueryFcn to obtain transaction information from the mirror nodes
- The function returns a mirror node REST API request about the relevant transaction (randNumInfo) and a string with a mirror explorer URL (randNumExpUrl)
- The input is the ID of the relevant transaction from the record object (randNumRec.transactionId)
- Output to the console:
- The random number obtained using both the transaction record and using the contract function
- A message indicating if the random number obtained with the two methods above matches or not
- The mirror node explorer URL with more details about the transaction
Console Output ✅
Console Output ✅
STEP 2 ===================================- Generating random number with Solidity…- Contract ID: 0.0.49020098- Contract ID in Solidity address format: 0000000000000000000000000000000002ebfcc2- Contract execution: SUCCESS- The random number (using transaction record) = 14- The random number (using contract function) = 14- The random number checks out ✅- See details in mirror node explorer:https://hashscan.io/testnet/transaction/0.0.2520793-1670012876-681938430