---
title: "How to Generate a Random Number on Hedera"
id: "15802"
type: "post"
slug: "how-to-generate-a-random-number-on-hedera"
published_at: "2022-12-05T09:00:00+00:00"
modified_at: "2025-12-08T18:51:12+00:00"
url: "https://hedera.com/blog/how-to-generate-a-random-number-on-hedera/"
markdown_url: "https://hedera.com/blog/how-to-generate-a-random-number-on-hedera.md"
excerpt: "Pseudorandom numbers are used in applications like lotteries, gaming, and even random selection in NFT giveaways. In this tutorial, you will learn how to generate random numbers on Hedera using the JavaScript SDK and Solidity."
taxonomy_category:
  - "Uncategorized"
taxonomy_post_tag:
  - "technical"
---

[Skip to content](#content)
blog

# How to Generate a Random Number on Hedera

December 5, 2022

Ed Marquez

Head of Developer Relations

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](https://hips.hedera.com/hip/hip-351#:~:text=a%20new%20transaction.-,Security%20Implications,-The%20pseudorandom%20number)
 (special mention and thanks to LG Electronics for the help and input formulating this Hedera Improvement Proposal).

By the way, [this resource](https://www.wolfssl.com/true-random-vs-pseudorandom-number-generation/)
 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.

#### **Try It Yourself**

- Get a [Hedera testnet account](https://portal.hedera.com/register)
  - This portal acts like a faucet, giving you 10,000 test HBAR every 24 hours
  - If you’re new to Hedera, check out [these steps to setup your development environment](https://docs.hedera.com/hedera/getting-started/environment-set-up)

- Use [this Codesandbox](https://codesandbox.io/s/hedera-example-random-number-y9q48r?file=/index.js) to try the example
  - Fork the sandbox
  - Remember to provide testnet account credentials in the .env file
  - Open a new terminal to execute index.js

- Get the [example code from GitHub](https://github.com/ed-marquez/hedera-example-random-number/blob/master/index.js)

#### **You Will Use These Tools**

- Hedera JavaScript SDK ([Documentation](https://docs.hedera.com/hedera/sdks-and-apis/sdks) )
- Solidity and libraries for random number generation ([HIP-351](https://hips.hedera.com/hip/hip-351) )
- Mirror node REST API ([Learn More](https://hedera.com/blog/how-to-look-up-transaction-history-on-hedera-using-mirror-nodes-back-to-the-basics) )
- Mirror node explorer ([HashScan](https://hashscan.io/#/mainnet/dashboard) )

#### **Follow These Steps**

1. Generate a random number using the SDK
2. Generate a random number using Solidity

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:

#### **1. Generate a Random Number Using the SDK**

Your testnet credentials from the [Hedera portal](https://portal.hedera.com/register)
 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()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/pseudorandom-number-generator) 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

```
// 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 
```

**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

#### **2. Generate a Random Number Using Solidity**

#### 2.1 Deploy the Contract

In the index.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***

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](https://hips.hedera.com/hip/hip-351#:~:text=mathematically%20ruled%20out.-,Reference%20Implementation,-The%20solidity%20precompiled)
. 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***.

**Helper Functions:**

The function ***contracts.deployContractFcn***uses [ContractCreateFlow()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/smart-contracts/create-a-smart-contract#contractcreateflow)
 to store the bytecode and deploy the contract on Hedera. This single call handles for you the operations [FileCreateTransaction()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/file-storage/create-a-file)
, [FileAppendTransaction()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/file-storage/append-to-a-file)
, and [ContractCreateTransaction()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/smart-contracts/create-a-smart-contract#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];
}
```

#### 2.2 Execute the 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

```
// 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`);
```

**Helper Functions:**

The function ***contracts.executeContractFcn***uses [ContractExecuteTransaction()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/smart-contracts/call-a-smart-contract-function)
 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;
}
```

#### 2.3 Get the Results – Query the Transaction Record, Call a Contract Function, and Check a Mirror Node Explorer

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](https://hedera.com/blog/how-to-look-up-transaction-history-on-hedera-using-mirror-nodes-back-to-the-basics) 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

The last step is to [join the Hedera Developer Discord!](https://hedera.com/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()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/transactions/get-a-transaction-record)
  
 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()](https://docs.hedera.com/hedera/sdks-and-apis/sdks/smart-contracts/call-a-smart-contract-function-1)
  
 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.

**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](https://hashscan.io/testnet/transaction/0.0.2520793-1670012876-681938430)

====================================================

THE END - NOW JOIN: [https://hedera.com/discord](https://hedera.com/discord)

====================================================

#### **Summary**

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.

#### **Continue Learning**

- [Open a Testnet Account](https://portal.hedera.com/register)
- [Try Examples](https://docs.hedera.com/hedera/tutorials) and [Tutorials](https://docs.hedera.com/hedera/tutorials)
- [Join the Developer Discord](http://hedera.com/discord)
- [Read the Learning Center](https://hedera.com/learning)

[Back to Blog](/blog)

discover

See more articles

[View All](/blog)

October 19, 2026

### Meet the Scaffold HBAR Template Bounty winners

Announcing the Scaffold-HBAR Template Bounty winners: templates for multisig governance, limit orders, scheduled keepers and recurring buys, each a command away.

[Read More](https://hedera.com/blog/meet-the-scaffold-hbar-template-bounty-winners/)

October 8, 2026

### Introducing Hedera Agent Accounts

Hedera Agent Accounts give AI agents programmable, non-custodial spending accounts on Hedera. Set limits and approved merchants on-chain, and your private keys never leave your wallet. This new approach measures

[Read More](https://hedera.com/blog/introducing-hedera-agent-accounts/)

October 1, 2026

### Introducing MirrorNodeAccountBalanceQuery: The SDK-Native Migration Path for AccountBalanceQuery

MirrorNodeAccountBalanceQuery is available now in the JavaScript, Java, and Go Hiero SDKs, giving developers a native way to read an account’s HBAR balance from the Mirror Node REST API without

[Read More](https://hedera.com/blog/mirrornodeaccountbalancequery-the-sdk-native-migration-path-for-accountbalancequery/)

## Ready to get started?

Discover why Hedera is the trusted institutional-grade network powering the new digital economy.

[Start Building](/start-building)

[Contact](/contact)

We use cookies to deliver the best experience on our website and to analyze traffic. By continuing to use this site, you consent to our cookie policy.

Review our [Privacy Policy](/privacy)
 to understand how Hedera collects and uses information.

Accept All CookiesAccept Necessary Cookies
