Hedera
  • Welcome to Hedera β€” let’s build the future
  • Getting Started
    • Environment Setup
    • Web2 Developers
      • Transfer HBAR
      • Create a Token
      • Create a Topic
    • EVM Developers
      • Deploy a Contract
  • Tutorials
    • Smart Contracts
      • How to Mint & Burn an ERC-721 Token Using Hardhat and Ethers (Part 1)
      • How to Set Access Control, a Token URI, Pause, and Transfer an ERC-721 Token Using Hardhat (Part 2)
      • How to Upgrade an ERC-721 Token with OpenZeppelin UUPS Proxies and Hardhat (Part 3)
      • How to Verify a Smart Contract on HashScan
      • Deploy a Smart Contract Using Remix
      • Deploy a Smart Contract Using Hardhat and Hiero JSON-RPC Relay
      • Deploy Your First Smart Contract
      • Deploy a Contract Using the Hedera Token Service
      • Send and Receive HBAR Using Solidity Smart Contracts
      • Deploy By Leveraging Ethereum Developer Tools On Hedera
      • Deploy a Subgraph Using The Graph and Hedera JSON-RPC Relay
      • Deploy Smart Contracts on Hedera Using Truffle
      • The Power of Native Hedera Tokens as ERC-20 Tokens: A step-by-step guide
      • HTS x EVM - Part 1: How to Mint NFTs
      • HTS x EVM - Part 2: KYC & Update
      • HTS x EVM - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Hedera Smart Contracts Workshop
        • Setup
        • Solidity
        • Hedera SDK JS
        • Hardhat and EthersJs
        • Outro
      • Foundry
        • How to Setup Foundry and Write a Basic Unit Test
        • How to Deploy and Verify a Hedera Smart Contract with Foundry
        • How to Test A Solidity Event
        • How to Fork Testnet on Latest Block
    • Consensus
      • Submit Your First Message
      • Submit Message to Private Topic
      • Query Messages with Mirror Node
    • Tokens
      • Create and Transfer Your First NFT
      • Create and Transfer Your First Fungible Token
      • Create and Transfer an NFT using a Solidity Contract
      • Structure Your Token Metadata Using JSON Schema V2
      • Hedera Token Service - Part 1: How to Mint NFTs
      • Hedera Token Service - Part 2: KYC, Update, and Scheduled Transactions
      • Hedera Token Service - Part 3: How to Pause, Freeze, Wipe, and Delete NFTs
      • Create Your First Frictionless Airdrop Campaign
    • Local Node
      • How to Run Hedera Local Node in a Cloud Development Environment (CDE)
        • Run a Local Node in Gitpod
        • Run a Local Node in Codespaces
      • How to Set Up a Hedera Local Node
      • Set Up a Hedera Local Node using the NPM CLI
    • More Tutorials
      • Create and Fund Your Hedera Testnet Account
      • How to Create a Personal Access Token (API Key) on the Hedera Portal
      • How to Auto-Create Hedera Accounts with HBAR and Token Transfers
      • How to Configure a Mirror Node and Query Data
      • How to Generate a Random Number on Hedera
      • Get Started with the Hedera Consensus Service Fabric Plugin
        • Virtual Environment Setup
      • Schedule Your First Transaction
      • How to Connect to Hedera Networks Over RPC
        • Configuring Hashio RPC endpoints
        • Configuring Hiero JSON-RPC Relay endpoints
        • Configuring Validation Cloud RPC endpoints
      • JavaScript Testing
      • Create a Hedera DApp Integrated with WalletConnect
      • How to Connect MetaMask to Hedera
    • Demo Applications
    • Starter Projects
    • Building on Hedera (course)
  • Networks
    • Mainnet
      • Mainnet Accounts
      • Mainnet Consensus Nodes
        • Node Requirements
          • FAQ
      • Fees
        • Transaction Records
    • Testnets
      • Testnet Accounts
      • Testnet Consensus Nodes
    • Localnet
      • Single Node Configuration
      • Multinode Configuration
    • Network Explorers and Tools
    • Release Notes
      • Consensus Node
      • Hedera Mirror Node
  • Core Concepts
    • Accounts
      • Account Creation
      • Auto Account Creation
      • Account Properties
    • Keys and Signatures
    • Schedule Transaction
    • Smart Contracts
      • Understanding Hedera's EVM Differences and Compatibility
        • For EVM Developers Migrating to Hedera
          • Accounts, Signature Verification & Keys (ECDSA vs. ED25519)
          • JSON-RPC Relay and EVM Tooling
          • Token Management with Hedera Token Service
          • Decimal Handling (8 vs. 18 Decimals)
          • Handling HBAR Transfers in Contracts
        • For Hedera-Native Developers Adding Smart Contract Functionality
          • Integrating ED25519 Accounts and Advanced Features Into Smart Contracts
          • JSON-RPC Relay and State Queries
          • Extending Token Management with Smart Contracts
      • Creating Smart Contracts
      • Compiling Smart Contracts
      • System Smart Contracts
        • Hedera Account Service
        • Hedera Schedule Service
      • Gas and Fees
      • JSON-RPC Relay
      • Deploying Smart Contracts
      • Smart Contract Addresses
      • Verifying Smart Contracts
      • Smart Contract Traceability
      • Tokens Managed by Smart Contracts
        • ERC-20 (Fungible Tokens)
        • ERC-721 (Non-Fungible Token)
        • ERC-3643 Real World Assets (RWA)
        • ERC-1363 (Payable Tokens)
        • Hedera Token Service System Contract
      • Wrapped HBAR (WHBAR)
      • Smart Contract Rent
      • Smart Contract Security
      • EVM Archive Node Queries
    • Tokens
      • Tokenization on Hedera
      • Hedera Token Service (HTS) Native Tokenization
        • Token Types and ID Formats
        • Token Properties
        • Token Creation
        • Custom Fee Schedule
        • Token Airdrops
      • ERC/EVM-Compatible Tokenization
      • Hybrid (HTS + EVM ) Tokenization
    • Staking
      • Staking Program
      • Stake HBAR
    • Hashgraph Consensus Algorithm
      • Gossip About Gossip
      • Virtual Voting
    • Transactions and Queries
      • Transaction Properties
    • State and History
    • Mirror Nodes
      • Hedera Mirror Node
      • One Click Mirror Node Deployment
      • Run Your Own Mirror Node
        • Run Your Own Mirror Node with Google Cloud Storage (GCS)
        • Run Your Mirror Node with Amazon Web Services S3 (AWS)
  • Open Source Solutions and Integrations
    • AI Tools for Developers
      • Hedera AI Agent Kit
      • ElizaOS Plugin for Hedera
      • Hedera Hivemind
      • Kapa AI
    • Asset Tokenization Studio (ATS)
      • Web User Interface (UI)
      • Frequently Asked Questions (FAQs)
    • HashioDAO
      • Governance Token DAO
      • NFT DAO
      • Multisig DAO
      • DAO Proposals
      • Local Environment Setup
    • Hedera CLI
    • Hedera Contract Builder
    • Hedera Custodians Library
      • How to use it
    • Hedera Developer Playground
    • Hedera Wallet Snap By MetaMask
      • Hedera Wallet Snap Documentation
      • Tutorial: MetaMask Snaps – What Are They and How to Use Them
    • Interoperability and Bridging
      • LayerZero
    • NFT Studio
      • Airdrop List Verifier
      • Metadata Validator
      • NFT Rarity Inspector
      • NFT Token Holders List Builder
      • NFT Risk Calculator
      • Token Balance Snapshot
      • Hedera NFT SDK
    • Oracle Networks
      • Chainlink Oracles
      • Pyth Oracles
      • Supra Oracles
    • Stablecoin Studio
      • Core Concepts
      • Web UI Application
      • CLI Management
      • TypeScript SDK
    • Hedera Guardian
    • Hedera WalletConnect
  • SDKs & APIs
    • SDKs
      • Build Your Hedera Client
      • Set Up Your Local Network
      • Network Address Book
      • Keys
        • Generate a new key pair
        • Import an existing key
        • Create a key list
        • Create a threshold key
        • Generate a mnemonic phrase
        • Recover keys from a mnemonic phrase
      • HBAR
      • Specialized Types
      • Pseudorandom Number Generator
      • Transactions
        • Create a Batch Transaction
        • Transaction ID
        • Modify transaction fields
        • Create an unsigned transaction
        • Manually sign a transaction
        • Submit a transaction
        • Sign a multisignature transaction
        • Get a transaction receipt
        • Get a transaction record
      • Schedule Transaction
        • Schedule ID
        • Create a schedule transaction
        • Sign a scheduled transaction
        • Delete a schedule transaction
        • Get schedule info
        • Network Response Messages
      • Queries
      • General Network Response Messages
      • Accounts and HBAR
        • Create an account
        • Update an account
        • Transfer cryptocurrency
        • Approve an allowance
        • Delete an allowance
        • Delete an account
        • Get account balance
        • Get account info
        • Network Response Messages
      • Consensus Service
        • Create a topic
        • Update a topic
        • Submit a message
        • Delete a topic
        • Get topic messages
        • Get topic info
        • Network Response
      • Token Service
        • Token ID
        • NFT ID
        • Token types
        • Create a token
        • Custom token fees
        • Update a token
        • Update token custom fees
        • Update NFT metadata
        • Transfer tokens
        • Airdrop a token
        • Claim a token
        • Cancel a token
        • Reject a token
        • Delete a token
        • Mint a token
        • Burn a token
        • Freeze an account
        • Unfreeze an account
        • Enable KYC account flag
        • Disable KYC account flag
        • Associate tokens to an account
        • Dissociate tokens from an account
        • Pause a token
        • Unpause a token
        • Wipe a token
        • Atomic swaps
        • Get account token balance
        • Get token info
        • Get NFT info
        • Network Response Messages
      • File Service
        • Create a file
        • Append to a file
        • Update a file
        • Delete a file
        • Get file contents
        • Get file info
        • Network Response Messages
      • Smart Contract Service
        • Delegate Contract ID
        • Create a smart contract
        • Update a smart contract
        • Delete a smart contract
        • Call a smart contract function
        • Ethereum transaction
        • Get a smart contract function
        • Get smart contract bytecode
        • Get smart contract info
        • Hedera Service Solidity Libraries
        • Network Response Messages
      • Signature Provider
        • Provider
        • Signer
        • Wallet
        • Local Provider
    • Mirror Node REST API
      • Accounts
      • Balances
      • Blocks
      • Schedule Transactions
      • Smart Contracts
      • Tokens
      • Topics
      • Transactions
      • Network
    • Hedera Consensus Service gRPC API
    • Hedera APIs
      • Basic Types
        • AccountAmount
        • AccountID
        • ContractID
        • CryptoAllowance
        • CurrentAndNextFeeSchedule
        • FeeComponents
        • FeeData
        • FeeSchedule
        • FileID
        • Fraction
        • HederaFunctionality
        • Key
        • KeyList
        • NftAllowance
        • NftTransfer
        • NodeAddress
        • NodeAddressBook
        • RealmID
        • ScheduleID
        • SemanticVersion
        • ServicesConfigurationList
        • ServiceEndpoint
        • Setting
        • ShardID
        • Signature
        • SignatureList
        • SignatureMap
        • SignaturePair
        • SubType
        • TransferList
        • TransactionID
        • ThresholdKey
        • ThresholdSignature
        • TokenAllowance
        • TokenBalance
        • TokenBalances
        • TokenFreezeStatus
        • TokenPauseStatus
        • TokenID
        • TokenKycStatus
        • TokenRelationship
        • TokenTransferList
        • TokenType
        • TokenSupplyType
        • TopicID
        • TransactionFeeSchedule
      • Cryptocurrency Accounts
        • CryptoService
        • CryptApproveAllowance
        • CryptoDeleteAllowance
        • CryptoCreate
        • CryptoTransfer
        • CryptoUpdate
        • CryptoDelete
        • CryptoGetAccountBalance
        • CryptoGetAccountRecords
        • CryptoGetInfo
        • CryptoGetStakers
      • Consensus Service
        • Consensus Service
        • ConsensusCreateTopic
        • ConsensusUpdateTopic
        • ConsensusSubmitMessage
        • ConsensusDeleteTopic
        • ConsensusTopicInfo
        • ConsensusGetTopicInfo
      • Schedule Service
        • ScheduleService
        • SchedulableTransactionBody
        • ScheduleCreate
        • ScheduleDelete
        • ScheduleSign
        • ScheduleGetInfo
      • Token Service
        • TokenService
        • CustomFees
          • AssessedCustomFee
          • CustomFee
          • FractionalFee
          • FixedFee
          • RoyaltyFee
        • TokenCreate
        • TokenUpdate
        • TokenFeeScheduleUpdate
        • TokenDelete
        • TokenMint
        • TokenBurn
        • TokenFreezeAccount
        • TokenUnfreezeAccount
        • TokenGrantKyc
        • TokenRevokeKyc
        • TokenAssociate
        • TokenDissociate
        • TokenWipeAccount
        • TokenPause
        • TokenUnpause
        • TokenGetInfo
        • TokenGetNftInfo
        • TokenGetNftInfos
        • TokenGetAccountNftInfo
      • File Service
        • FileService
        • FileCreate
        • FileAppend
        • FileUpdate
        • FileDelete
        • FileGetContents
        • FileGetInfo
      • Smart Contracts
        • SmartContractService
        • ContractCall
        • ContractCallLocal
        • ContractCreate
        • ContractUpdate
        • ContractDelete
        • ContractGetByteCode
        • ContractGetInfo
        • ContractGetRecords
      • Miscellaneous
        • Duration
        • ExchangeRate
        • Freeze
        • FreezeType
        • GetByKey
        • GetBySolidityID
        • NetworkGetVersionInfo
        • NetworkService
        • Query
        • QueryHeader
        • Response
        • ResponseCode
        • ResponseHeader
        • SystemDelete
        • SystemUndelete
        • TimeStamp
        • Transaction
        • TransactionBody
        • TransactionContents
        • TransactionGetFastRecord
        • TransactionGetReceipt
        • TransactionGetRecord
        • TransactionReceipt
        • TransactionRecord
        • TransactionResponse
        • UncheckedSubmit
    • Hedera Status API
  • Support & Community
    • Glossary
    • Contributing to Hedera documentation
      • Contribution Guidelines
        • Creating Issues
        • Creating Pull Requests
        • Hedera Improvement Proposal (HIP)
        • Submit Demo Applications
      • Style Guide
        • Understanding different types of documentation
        • Use of HBAR and tinybars
        • Use of web2 and web3
        • Language and grammar
        • Formatting
        • Punctuation
        • GitBook Markdown Syntax
    • Discord
    • GitHub
    • Stack Overflow
    • Hedera Blog
    • Bug Bounty
    • Hedera Help
    • Documentation Survey
    • Meetups
    • Brand Guidelines
    • Status Page
Powered by GitBook
LogoLogo

INTRODUCTION

  • Fees
  • Core Concepts
  • Network Information

TOOLS

  • Bridge
  • Oracles
  • Explorers
  • Developer Portal & Faucet

RESOURCES

  • Status
  • Bug Bounty
  • Build on Hedera (course)
  • Documentation Survey
On this page
  • Prerequisites
  • Table of Contents
  • Generate Random Numbers Using the SDK
  • Generate Random Numbers Using Solidity
  • Deploy Contract
  • Execute Contract
  • Query Results
  • Summary
  • Additional Resources

Was this helpful?

Edit on GitHub
  1. Tutorials
  2. More Tutorials

How to Generate a Random Number on Hedera

PreviousHow to Configure a Mirror Node and Query DataNextGet Started with the Hedera Consensus Service Fabric Plugin

Last updated 4 months ago

Was this helpful?

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 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 (special mention and thanks to LG Electronics for the help and input in formulating this Hedera Improvement Proposal).

This 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.


Prerequisites

  • Get a account .

  • Get the .

  • Set up your environment and create a client .

πŸ“£ Note: This tutorial requires the use of the following tools: Hedera , Solidity with libraries for random number generation (), and the Mirror Node REST API () and explorer ().


Table of Contents


Generate Random Numbers Using the SDK

  • 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

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


Generate Random Numbers Using Solidity

Deploy 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

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

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

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;
}

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

// 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.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]}`;
}
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:


Summary


Additional Resources

Step 1: The Operator is the only account involved in submitting transactions to the Hedera network. Your testnet credentials from the should be used for the operator variables, which are used to initialize the Hedera client that submits transactions to the network and gets confirmations.

Use in the SDK to create a transaction that generates a pseudorandom number

Step 2: Deploy a Solidity smart contract to generate the random number. After completing all steps, your console should look something like .

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

The function contracts.deployContractFcn uses to store the bytecode and deploy the contract on Hedera. This single call handles for you the operations , , and . This helper function simplifies the contract deployment process and is reusable in case you need to create more contracts in the future.

The function contracts.executeContractFcn uses in the SDK to call the specified contract function.

The function returns a request about the relevant transaction (randNumInfo) and a string with a mirror explorer URL (randNumExpUrl)

The function queries.txRecordQueryFcn uses 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 in the SDK to call a contract function that reads a state variable containing the random number.

Now you know how to generate a random number on Hedera using the JavaScript SDK and Solidity libraries. Try this example with the other officially supported for Java, Go, and Swift (coming soon).

Congratulations! πŸŽ‰ You have successfully learned how to generate a random number on Hedera. Feel free to reach out on if you have any questions!

➑

➑

Hedera portal
PrngTransaction()
HIP-351
ContractCreateFlow()
FileCreateTransaction()
FileAppendTransaction()
ContractCreateTransaction()
ContractExecuteTransaction()
mirror node REST API
TransactionRecordQuery()
ContractCallQuery()
https://hashscan.io/testnet/transaction/0.0.2520793-1670012876-681938430
Discord
Project Repository
WolfSSL Random Number Guide
this

Writer: Ed, DevRel Engineer

Editor: Krystal, Technical Writer

HIP-351
resource
Hedera Testnet
here
example code from GitHub
here
JavaScript SDK
HIP-351
learn more
HashScan
Generate Random Numbers (SDK)
Generate Random Numbers (Solidity)
Deploy Contract
Execute Contract
Query Results
Summary
Additional Resources

|

|

GitHub
LinkedIn
GitHub
Twitter
JavaScript SDK
SDKs