best-practices.mdx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. ---
  2. title: Best Practices
  3. description: Best practices for using Pyth Entropy in your applications
  4. ---
  5. # Best Practices
  6. ## Limit gas usage on the callback
  7. Keeping the callback function simple is crucial because the entropy providers limit gas usage.
  8. This ensures gas usage is predictable and consistent, avoiding potential issues with the callback.
  9. For example, if you want to use entropy to generate a random number for each player in a round of game,
  10. you need to make sure that the callback function works for the maximum number of players that can be in each round.
  11. Otherwise, the callbacks will work for some rounds with fewer players, but will fail for rounds with more players.
  12. Multiple solutions are possible to address this problem. You can store the random number received from the callback and
  13. either ask users to submit more transactions after the callback to continue the flow or run a background crank service
  14. to submit the necessary transactions.
  15. The gas limit for each chain is listed on the [contract addresses](contract-addresses) page.
  16. ## Handling callback failures
  17. While the default entropy provider is highly reliable, in rare cases a callback might not be received. This typically happens when there's an issue with your contract's callback implementation rather than with the provider itself. The most common causes are:
  18. 1. The callback function is using more gas than the allowed limit
  19. 2. The callback function contains logic that throws an error
  20. If you're not receiving a callback, you can manually invoke it to identify the specific issue. This allows you to:
  21. - See if the transaction fails and why
  22. - Check the gas usage against the chain's callback gas limit
  23. - Debug your callback implementation
  24. For detailed instructions on how to manually invoke and debug callbacks, refer to the [Debug Callback Failures](debug-callback-failures) guide.
  25. ## Generating random values within a specific range
  26. 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).
  27. Here is a simple example of how to map a random number provided by Entropy into a range between `minRange` and `maxRange` (inclusive).
  28. ```solidity
  29. // Maps a random number into a range between minRange and maxRange (inclusive)
  30. function mapRandomNumber(
  31. bytes32 randomNumber,
  32. int256 minRange,
  33. int256 maxRange
  34. ) internal pure returns (int256) {
  35. require(minRange <= maxRange, "Invalid range");
  36. uint256 range = uint256(maxRange - minRange + 1);
  37. uint256 randomUint = uint256(randomNumber);
  38. return minRange + int256(randomUint % range);
  39. }
  40. ```