best-practices.mdx 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. ---
  2. title: Best Practices
  3. description: Best practices for using Pyth Entropy in your applications
  4. ---
  5. ## Generating random values within a specific range
  6. You can map the random number provided by Entropy into a smaller range using the solidity [modulo operator](https://docs.soliditylang.org/en/latest/types.html#modulo).
  7. Here is a simple example of how to map a random number provided by Entropy into a range between `minRange` and `maxRange` (inclusive).
  8. ```solidity
  9. // Maps a random number into a range between minRange and maxRange (inclusive)
  10. function mapRandomNumber(
  11. bytes32 randomNumber,
  12. int256 minRange,
  13. int256 maxRange
  14. ) internal pure returns (int256) {
  15. require(minRange <= maxRange, "Invalid range");
  16. uint256 range = uint256(maxRange - minRange + 1);
  17. uint256 randomUint = uint256(randomNumber);
  18. return minRange + int256(randomUint % range);
  19. }
  20. ```
  21. Notice that using the modulo operator can distort the distribution of random numbers if it's not a power of 2. This is
  22. negligible for small and medium ranges, but it can be noticeable for large ranges.
  23. For example, if you want to generate a random number between 1 and 52, the probability of having value 5 is approximately
  24. `10^-77` higher than the probability of having value 50 which is infinitesimal.
  25. ## Generating multiple random values in a single transaction
  26. If you need to generate multiple random values in a single transaction, you can hash the random input provided by Entropy with a unique identifier for each random number.
  27. In the following example, `mapRandomNumber` is used to generate 6 random attributes for a character.
  28. ```solidity
  29. function generateAttributes(bytes32 randomNumber) internal {
  30. int256 strength = mapRandomNumber(
  31. keccak256(abi.encodePacked(randomNumber, "strength")),
  32. 15,
  33. 20
  34. );
  35. int256 stamina = mapRandomNumber(
  36. keccak256(abi.encodePacked(randomNumber, "stamina")),
  37. 10,
  38. 15
  39. );
  40. int256 agility = mapRandomNumber(
  41. keccak256(abi.encodePacked(randomNumber, "agility")),
  42. 5,
  43. 15
  44. );
  45. int256 stealth = mapRandomNumber(
  46. keccak256(abi.encodePacked(randomNumber, "stealth")),
  47. 0,
  48. 5
  49. );
  50. int256 positionX = mapRandomNumber(
  51. keccak256(abi.encodePacked(randomNumber, "positionX")),
  52. -100,
  53. 100
  54. );
  55. int256 positionY = mapRandomNumber(
  56. keccak256(abi.encodePacked(randomNumber, "positionY")),
  57. -100,
  58. 100
  59. );
  60. }
  61. ```