Home » Answers » How to generate a random number in Solidity?

# How to generate a random number in Solidity? Number generation in Solidity is the process of creating random numbers within a Solidity smart contract. This can be used for various purposes, such as generating unique IDs for objects, creating random outcomes in games, or selecting random participants for a lottery.

Number generation is an important feature of Solidity as it allows for greater flexibility and functionality in smart contracts.

## Follow these steps to generate a random number in Solidity

### 1. Import the `keccak256` library by adding the following line to the beginning of your contract

``````pragma solidity ^0.4.24;
import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "https://github.com/OpenZeppelin/openzeppelin-solidity/contracts/cryptography/Keccak256.sol";
``````

### 2. Create a function named `generateRandomNumber` that takes in no arguments and returns a `uint` value

``````function generateRandomNumber() public view returns (uint) {
// code to generate random number goes here
}
``````

### 3. Inside the `generateRandomNumber` function, create a variable named `timestamp` that stores the current block’s timestamp

This can be obtained using the `block.timestamp` variable.

``````function generateRandomNumber() public view returns (uint) {
uint timestamp = block.timestamp;
}
``````

### 4. Use the `keccak256` library to hash the `timestamp` variable and store the resulting hash in a `bytes32` variable named `hash`

``````function generateRandomNumber() public view returns (uint) {
uint timestamp = block.timestamp;
bytes32 hash = keccak256(abi.encodePacked(timestamp));
}
``````

### 5. Use the `bytes32` type’s `uint()` function to convert the `hash` value to a `uint` value and return it

``````function generateRandomNumber() public view returns (uint) {
uint timestamp = block.timestamp;
bytes32 hash = keccak256(abi.encodePacked(timestamp));
return hash.uint();
}
``````

### 6. To use this function in your contract, simply call it and store the returned value in a `uint` variable

For example:

``````function someFunction() public {
uint randomNumber = generateRandomNumber();
}
``````

Note: The randomness of this method is dependent on the block timestamp, which is not necessarily truly random. It is recommended to use a more secure method of generating random numbers, such as using a random number oracle service.

Hopefully this answer helps you understand how to generate a random number in Solidity. If you have any suggestions, feedback or got something nice to say – leave a comment below and say hi 👋🏼