 Hello,

I found this code while searching for solution to random number generation for a Dice roll.

``````    function fulfillRandomness(bytes32 requestId, uint256 randomness) external override {
emit RequestRandomnessFulfilled(requestId, randomness);
}
``````

The above code is created using Chainlink’s Random number generator Smart Contract. I would like to understand this specific code in that section:

``````randomness.mod(6).add(1);
``````

How does the above code work? What is mod() function over here. Does this return random number only between 1 to 6 or 0 to 5 ? If I need to get a random numbers between 1 to 3, which is 1 or 2 or 3, should I use the following line? Is it correct?

``````randomness.mod(3).add(1);
``````

Thank you.

Regards,
Harish

1 Like

If that the SafeMath methode…

e.g.
randomness=10
randomness.mod(6) = 4

randomness=10
randomness.mod(3) = 1

So mod() is modolu (at: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol) … so the rest of a division.
10/6 rest = 4
5/4 rest = 1
16/5 rest = 1 , …

Hope I’m right because you dont show the imports^^

1 Like

Hello,

Sorry for not specifying the import. Here is the file which is being imported. I think its the same as OpenZepplin’s SafeMath.sol.

As I understand from your description, the mod() function returns the reminder. For example, 10 divide by 4, you get 2 as reminder.

Can you let me know exactly the code that I need to use if I have to get a random number between 1 and 3, which is 1 or 2 or 3 ?

Regards,
Harish

1 Like

Hello,

ahh reminder is the english word? Sorry for my bad english.

there are many ways to do so … the most esaiest would be if you set

`randomness.mod(3).add(1);`

.mod(3) gives you everytime something between 0-2 and .add(1) make this numbers to 1-3 …

And here is a point where Im also not sure how solidity behavior is:
But keep in mind that the highes number of randomnes should be a number where .mod(3) = 2

because:
number = 0
number.mod(3) = 0

Normaly… dont know how solidity are behave… so you start with 0 and if your number series of possible “randomnes” numbers don’t end with .mod(3) = 2 you have a 0 more and so a higher chance to get 0 than the other numbers…(In your case if you .add(1) than the 1 …) also is this behavior, when its simular in solidity like in other languages (I see no point why not), when the highest number is .mod(3) = 1 than you have one more 0 and one more 1 … Hope you understand what I mean.

1 Like

Thank you. 1 Like