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 formulating this Hedera Improvement Proposal).
By the way, 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.
In this scenario, the Operator is the only account involved in submitting transactions to the Hedera network. In step 2, you deploy a smart contract to generate the random number. After completing all steps, your console should look something like this:
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.
// STEP 1 =================================== console.log(`\nSTEP 1 ===================================\n`); console.log(`- Generating random numbers with the SDK...\n`); const lo = 0; const hi = 50; let randomNum = []; for (var i = 0; i < 5; i++) { const randomNumTx = await new PrngTransaction().setRange(hi).execute(client); const randomNumRec = await randomNumTx.getRecord(client); randomNum[i] = randomNumRec.prngNumber; console.log(`- Run #${i + 1}: Random number = ${randomNum[i]}`); }
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
In the index.js file:
You can see the Solidity contract PrngSystemContract in the second tab below. This example calls a precompiled contract with address 0x169. For additional details about the contract and the functions getPseudorandomSeed and getPseudorandomNumber, check out HIP-351. The first function generates a 256-bit pseudorandom seed and returns the corresponding bytes; you can then use that seed to get a random number. The second function operates on those bytes to return the random number. There is also a contract function getNumber which reads the random number from the contract state variable, randNum.
// STEP 2 =================================== console.log(`\nSTEP 2 ===================================\n`); console.log(`- Generating random number with Solidity...\n`); // Deploy the Solidity contract let gasLim = 4000000; const bytecode = contract.object; const [contractId, contractAddress] = await contracts.deployContractFcn(bytecode, gasLim, client); console.log(`- Contract ID: ${contractId}`); console.log(`- Contract ID in Solidity address format: ${contractAddress}`);
// SPDX-License-Identifier: Apache-2.0 pragma solidity >=0.4.9 <0.9.0; import "./IPrngSystemContract.sol"; contract PrngSystemContract { address constant PRECOMPILE_ADDRESS = address(0x169); uint32 randNum; function getPseudorandomSeed() external returns (bytes32 randomBytes) { (bool success, bytes memory result) = PRECOMPILE_ADDRESS.call( abi.encodeWithSelector(IPrngSystemContract.getPseudorandomSeed.selector)); require(success); randomBytes = abi.decode(result, (bytes32)); } /** * Returns a pseudorandom number in the range [lo, hi) using the seed generated from "getPseudorandomSeed" */ function getPseudorandomNumber(uint32 lo, uint32 hi) external returns (uint32) { (bool success, bytes memory result) = PRECOMPILE_ADDRESS.call( abi.encodeWithSelector(IPrngSystemContract.getPseudorandomSeed.selector)); require(success); uint32 choice; assembly { choice := mload(add(result, 0x20)) } randNum = lo + (choice % (hi - lo)); return randNum; } function getNumber() public view returns (uint32) { return randNum; } }
Helper Functions:
The function contracts.deployContractFcn uses ContractCreateFlow() to store the bytecode and deploy the contract on Hedera. This single call handles for you the operations FileCreateTransaction(), FileAppendTransaction(), and ContractCreateTransaction(). This helper function simplifies the contract deployment process and is reusable in case you need to create more contracts in the future.
export async function deployContractFcn(bytecode, gasLim, client) { const contractCreateTx = new ContractCreateFlow().setBytecode(bytecode).setGas(gasLim); const contractCreateSubmit = await contractCreateTx.execute(client); const contractCreateRx = await contractCreateSubmit.getReceipt(client); const contractId = contractCreateRx.contractId; const contractAddress = contractId.toSolidityAddress(); return [contractId, contractAddress]; }
// Execute the contract const randNumParams = new ContractFunctionParameters().addUint32(lo).addUint32(hi); const randNumRec = await contracts.executeContractFcn(contractId, "getPseudorandomNumber", randNumParams, gasLim, client); console.log(`- Contract execution: ${randNumRec.receipt.status} \n`);
The function contracts.executeContractFcn uses ContractExecuteTransaction() in the SDK to call the specified contract function.
export async function executeContractFcn(cId, fcnName, params, gasLim, client) { const contractExecuteTx = new ContractExecuteTransaction().setContractId(cId).setGas(gasLim).setFunction(fcnName, params); const contractExecuteSubmit = await contractExecuteTx.execute(client); const contractExecuteRec = await contractExecuteSubmit.getRecord(client); return contractExecuteRec; }
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.
The last step is to join the Hedera Developer Discord!
// Query the transaction record to get the random number from bytes const recQuery = await queries.txRecQueryFcn(randNumRec.transactionId, client); let lowOrderBytes = new Uint8Array(recQuery.children[0].prngBytes).slice(28, 32); let dataview = new DataView(lowOrderBytes.buffer); let range = hi - lo; let int32be = dataview.getUint32(0); let randNum = int32be % range; console.log(`- The random number (using transaction record) = ${randNum}`); // Call the contract to read random number using the getNumber function const randNumResult = await contracts.callContractFcn(contractId, "getNumber", gasLim, client); console.log(`- The random number (using contract function) = ${randNumResult.getUint32(0)}`); randNum === randNumResult.getUint32(0) ? console.log(`- The random number checks out ✅`) : console.log(`- Random number doesn't match ❌`); // Check a Mirror Node Explorer const [randNumInfo, randNumExpUrl] = await queries.mirrorTxQueryFcn(randNumRec.transactionId); console.log(`\n- See details in mirror node explorer: \n${randNumExpUrl}`); console.log(` ==================================================== THE END - NOW JOIN: https://hedera.com/discord ====================================================\n`); }
Helper Functions
The function queries.txRecordQueryFcn uses TransactionRecordQuery() in the SDK to obtain details about the contract execution transaction. Note that the .setIncludeChildren method is set to true to get information about all the children transactions under the contract execution – this includes the transaction generating the random number.
The function contracts.callContractFcn uses ContractCallQuery() in the SDK to call a contract function that reads a state variable containing the random number.
The function queries.mirrorTxQueryFcn obtains transaction information from the mirror nodes. The function introduces a delay of 10 seconds to allow for the propagation of information to the mirror nodes. It then formats the transaction ID and performs string operations to return a mirror REST API query and a mirror node explorer URL.
export async function txRecQueryFcn(txId, client) { const recQuery = await new TransactionRecordQuery().setTransactionId(txId).setIncludeChildren(true).execute(client); return recQuery; }
export async function callContractFcn(cId, fcnName, gasLim, client) { const contractCallTx = new ContractCallQuery().setContractId(cId).setGas(gasLim).setFunction(fcnName); const contractCallSubmit = await contractCallTx.execute(client); return contractCallSubmit; }
export async function mirrorTxQueryFcn(txIdRaw) { // Query a mirror node for information about the transaction const delay = (ms) => new Promise((res) => setTimeout(res, ms)); await delay(10000); // Wait for 10 seconds before querying a mirror node const txIdPretty = prettify(txIdRaw.toString()); const mirrorNodeExplorerUrl = `https://hashscan.io/testnet/transaction/${txIdPretty}`; const mirrorNodeRestApi = `https://testnet.mirrornode.hedera.com/api/v1/transactions/${txIdPretty}`; let mQuery = []; try { mQuery = await axios.get(mirrorNodeRestApi); } catch {} return [mQuery, mirrorNodeExplorerUrl]; } function prettify(txIdRaw) { const a = txIdRaw.split("@"); const b = a[1].split("."); return `${a[0]}-${b[0]}-${b[1]}`; }
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
====================================================
🎉🎉 THE END - NOW JOIN: https://hedera.com/discord
Now you know how to generate a random number on Hedera using the JavaScript SDK and Solidity libraries. You can try this example with the other officially supported SDKs for Java, Go, and Swift.